Reduce a sequence of items provided by a generator in JavaScript - Stack Overflow

Say I have a sequence of items and I want to perform a reduce operation via myReducer function (whateve

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
Add a ment  | 

2 Answers 2

Reset to default 8

For 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信