Passing a math operator as a parameter

You can’t pass an operator as a parameter, but you can pass a function:

function accumulate(list, accumulator){   // renamed parameter
    var sum = 0;
    for(var i = 0; i < list.length; i++){ // removed deprecated for…each loop
        sum = accumulator(sum, list[i]);
    }
    print(sum);
}

accumulate(list, function(a, b) { return a + b; });

This is pretty close to what the Array.prototype.reduce function does, though not exactly. To mimic the behavior of reduce, you’d have to get the first element from list and use that as the seed for your accumulator, rather than always using 0:

function accumulate(list, accumulator, seed){
    var i = 0, len = list.length;
    var acc = arguments.length > 2 ? seed : list[i++];
    for(; i < len; i++){
        acc = accumulator(acc, list[i]);
    }
    print(acc);
}

This way, you could compute the product of list (your method would always return 0):

accumulate(list, function(a, b) { return a * b; });

Update: If you’re developing for newer browsers that support ECMAScript 2015 / ES6 (or using a transpiler like Babel), you can also use ‘arrow function’ syntax to make your code a bit more compact:

accumulate(list, (a, b) => a * b);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)