2

Suppose I have the following Javascript code:

    var i = 0;

    var list = ['a','b','c'];

    for (var key in list) {
        
        // some other operations on list[key]

        // in case they are successful
        i = i + 1;
        
    }

    if (i == list.length) {
        console.log('cycle complete');
    }

The idea is that a certain function (in this case console.log) fires after the cycle is complete.

What would be a more efficient way to achieve the same tasks?

Maybe functional programming?

Aerodynamika
  • 7,883
  • 16
  • 78
  • 137

1 Answers1

1

Assuming the operation in your for loop will evaluate to true or false, you could do something like this:

function countSucceeded(list: any[], iteratee: (key: string) => boolean): number {
    let count = 0;

    for (let i = 0; i < list.length; i++) {
        if (iteratee(list[i])) {
            count++;
        }
    }

    return count;
}

const list = ['foo', 'bar', 'baz'];
const test = (key: string): boolean => key.indexOf('foo') > -1;
const count = countSucceeded(list, test);

console.log(count); // 1

Now it is "functional", though you could get rid of the loop as well.

Update:

Here is how you could do the loop in a purely functional way:

function each(list, iteratee) {
    if (list.length == 0) {
            return;
    }

    iteratee(list.shift())

    return each(list, iteratee);
}

each([1, 2, 3], num => console.log(num)); // 1 2 3
Lansana Camara
  • 9,497
  • 11
  • 47
  • 87