admin管理员组文章数量:1333442
Say I have a sequence of items and I want to perform a reduce operation via myReducer
function (whatever it is). If my items are in an array (say myArray
), it's easy:
myArray.reduce(myReducer);
What if, however, my sequence is quite large and I don't want to allocate an array of all of it, only to immediately reduce it item after item? I can create a generator function for my sequence, that part is clear. Is there a straightforward way of how to then perform the reduction? I mean apart from writing the reduce functionality for a generator myself.
Say I have a sequence of items and I want to perform a reduce operation via myReducer
function (whatever it is). If my items are in an array (say myArray
), it's easy:
myArray.reduce(myReducer);
What if, however, my sequence is quite large and I don't want to allocate an array of all of it, only to immediately reduce it item after item? I can create a generator function for my sequence, that part is clear. Is there a straightforward way of how to then perform the reduction? I mean apart from writing the reduce functionality for a generator myself.
Share Improve this question asked Nov 23, 2018 at 16:19 OndraOndra 2001 silver badge9 bronze badges 1- You need to create a lazy evaluation array object/class with a lazy evaluation reduce. – Dominique Fortin Commented Nov 23, 2018 at 16:26
2 Answers
Reset to default 8For now, ECMA-Script standard provides functions like reduce
for arrays, so you're out of luck: you need to implement your own reduce
for iterables:
const reduce = (f, i, it) => {
let o = i
for (let x of it)
o = f (o, x)
return o
}
const xs = [1, 2, 3]
const xs_ = {
[Symbol.iterator]: function* () {
yield 1
yield 2
yield 3
}
}
const output1 = reduce ((o, x) => o + x, 10, xs)
const output2 = reduce ((o, x) => o + x, 10, xs_)
console.log ('output1:', output1)
console.log ('output2:', output2)
Update as of 8/2024: Support for iterator reducing and other array-like helpers are in the works but experimental: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/reduce. Support is hit or miss, but promising.
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
console.log(
fibonacci()
.take(10)
.reduce((a, b) => a + b),
); // 143
本文标签: Reduce a sequence of items provided by a generator in JavaScriptStack Overflow
版权声明:本文标题:Reduce a sequence of items provided by a generator in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742286302a2446990.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论