javascript - Passing a math operator as a parameter -
i'd write function in javascript allows me pass in mathematical operator , list of ints , each item in list, apply operator it.
thinking of in terms of sum, i've come with:
function accumulate(list, operator){ var sum = 0; each(var item in list){ sum = accumulator(sum, item); } print(sum); } testing code produces following error:
var list = new array(); list[0] = 1; list[1] = 2; list[2] = 3; js> accumulate(list, +); js: "<stdin>", line 9: syntax error js: accumulate(list, +); js: ..................^ js: "<stdin>", line 9: compilation produced 1 syntax errors.
you can't pass operator parameter, can pass function:
function accumulate(list, accumulator){ // renamed parameter var sum = 0; for(var = 0; < list.length; i++){ // removed deprecated for…each loop sum = accumulator(sum, list[i]); } print(sum); } accumulate(list, function(a, b) { return + b; }); this pretty close array.prototype.reduce function does, though not exactly. mimic behavior of reduce, you'd have first element list , use seed accumulator, rather using 0:
function accumulate(list, accumulator, seed){ var = 0, len = list.length; var acc = arguments.length > 2 ? seed : list[i++]; for(; < len; i++){ acc = accumulator(acc, list[i]); } print(acc); } this way, compute product of list (your method return 0):
accumulate(list, function(a, b) { return * b; });
Comments
Post a Comment