3 回答

TA贡献1890条经验 获得超9个赞
很多,通过保持运行总数:
function* partialSums(iterable) {
let s = 0;
for (const x of iterable) {
s += x;
yield s;
}
}
const x = [0, 1, 2, 3, 4, 5];
console.log(Array.from(partialSums(x)).join(', '));
线性时间,在线。(您也可以直接生成数组;在下面展开。)
const partialSums = arr => {
let s = 0;
return arr.map(x => s += x);
};
const x = [0, 1, 2, 3, 4, 5];
console.log(partialSums(x).join(', '));

TA贡献1852条经验 获得超1个赞
平面地图在您的情况下没有用,因为您不会试图将作为列表出现的部分结果展平,但我们可能会尝试在单个reduce 中解决您的问题:
[0, 1, 2, 3, 4, 5]
.reduce(
([arr, sum], el) => { // We pass along array and running sum
const next = sum + el
return [[...arr, next], next]
},
[[], 0] // We need to seed our reduce with empty array and accumulator for calculating running sum
)[0] // Array containing array and the last sum is returned, so we need to take only the first element
它还只迭代数组一次,因此与创建切片然后对它们求和的解决方案相比,它的性能可能更高一些。
或者带有 的版本array.push,它重用相同的数组:
[0, 1, 2, 3, 4, 5]
.reduce(
([arr, sum], el) => { // We pass along array and running sum
const next = sum + el
arr.push(next)
return [arr, next]
},
[[], 0] // We need to seed our reduce with empty array and accumulator for calculating running sum
)[0]
添加回答
举报