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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742286303a4415383.html
评论列表(0条)