相当于Clojure的“减少”或python的itertools.accumulate的Javascript
作者:互联网
是否有与Clojure的“减少”功能等效的JavaScript或Python的itertools.accumulate?换句话说,给定一个数组[x_0,x_1,x_2 … x_n-1]和一个函数f(prev,next),它将返回一个长度为n的数组,其值如下:
[x_0,f(x_0,x_1),f(f(x_0,x_1),x_2)… f(f(f(…)),x_n)]
我在下面模拟所需的行为:
function accumsum(prev, next) {
last = prev[prev.length - 1] || 0;
prev.push(last + next);
return prev;
}
var x = [1, 1, 1, 1];
var y = x.reduce(accumsum, []);
var z = y.reduce(accumsum, []);
console.log(x);
console.log(y);
console.log(z);
显示:
[ 1, 1, 1, 1 ]
[ 1, 2, 3, 4 ]
[ 1, 3, 6, 10 ]
但是我想知道是否有一种方法可以编写像
[1, 1, 1, 1].reductions(function(prev, next) {return prev + next;});
如果没有,那么在JavaScript中是否有比我写的更惯用的方法?
解决方法:
var a = [1, 1, 1, 1];
var c = 0;
a.map(function(x) { return c += x; })
// => [1, 2, 3, 4]
a.reduce(function(c, a) {
c.push(c[c.length - 1] + a);
return c;
}, [0]).slice(1);
// => [1, 2, 3, 4]
我会亲自使用第一个.
编辑:
Is there a way of doing your first suggestion that doesn’t require me to have a random global variable (c in this case) floating around? If I forgot to re-initialize c back to 0, the second time I wrote a.map(…) it would give the wrong answer.
当然-您可以封装它.
function cumulativeReduce(fn, start, array) {
var c = start;
return array.map(function(x) {
return (c = fn(c, x));
});
}
cumulativeReduce(function(c, a) { return c + a; }, 0, [1, 1, 1, 1]);
// => [1, 2, 3, 4]
c
// => ReferenceError - no dangling global variables
标签:clojure,reduce,javascript,python,functional-programming 来源: https://codeday.me/bug/20191119/2037045.html