javascript - Reduce with higher-order callback parameter -
i have tried many ways parent parameter visible reduce's callback function must missing something...
// static var y = [0, 1, 2, 3, 4, 5, 6, 7].reduce( function(arr, x){ arr.push(math.pow(2, x)); return arr},[]); console.log(y); // dynamic var lambda = function(arr, func) { return (function(f) { return arr.reduce(function(a, x) { a.push(f(x)); return a; }, [])})(func); } var y = lambda([0, 1, 2, 3, 4, 5, 6, 7],function(x){return math.pow(x);}); console.log(y);
output:
[1, 2, 4, 8, 16, 32, 64, 128] [nan, nan, nan, nan, nan, nan, nan, nan]
you missing 1 of parameters math.pow
. might wanna invoke lambda
this
var y = lambda([0, 1, 2, 3, 4, 5, 6, 7], function(x) { return math.pow(2, x); });
also, don't have complicate lambda
construction iife. can simply
var lambda = function(arr, func) { return arr.reduce(function(a, x) { a.push(func(x)); return a; }, []); }
edit: suggested in comments can use array.prototype.map
, this
console.log(arr.map(function(x) { return math.pow(2, x); }));
Comments
Post a Comment