Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce a sequence of items provided by a generator in JavaScript

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.

like image 464
Ondra Avatar asked Nov 23 '18 16:11

Ondra


1 Answers

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)
like image 58
Matías Fidemraizer Avatar answered Oct 21 '22 22:10

Matías Fidemraizer