Lesleh Lesleh - 4 months ago 32
Javascript Question

Using ES5 array methods with ES6 generators

What's the correct way of using the new ES5 array functions with ES6 generators? Do I have to explicitly convert the iterable into an array first, or is there a better way? For example:

function* range(low, high) {
var i = low;
while(i < high)
yield i++;

// Sum of numbers in range, doesn't work
console.log(range(0, 10).reduce((x,y) => x + y));


Generator functions return Iterator objects. The Iterator API does not include higher order Array methods such as map, reduce etc, so you need to build an intermediate Array (or use a library like wu.js).

You can use the spread operator to concisely build an Array from a (finite) iterator:

var sum = [...range(0, 10)].reduce((e, i) => e + i)