Why do generators not support map()?

Why do generators not support map()?

Because it’s too easy to fill in as a userland implementation. ES3 didn’t include Array iteration methods either, maybe will see transformers for iterators in ES7 🙂

generators, which function very much like Arrays

No, please stop and distinguish iterators from generators:

  • An iterator is an object with a .next() method that conforms to the iterator protocol.
  • A generator is an iterator created by a generator function (function*). Its .next() method takes an argument which is the result of each yield inside the generator function. It also has .return() and .throw() methods.

You’ll mostly be interested in iterators, where we don’t pass values to next, and don’t care about the end result – just like for of loops do. We can extend them with the desired methods easily:

var IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
IteratorPrototype.map = function*(f) {
    for (var x of this)
        yield f(x);
};
IteratorPrototype.filter = function*(p) {
    for (var x of this)
        if (p(x))
            yield x;
};
IteratorPrototype.scan = function*(f, acc) {
    for (var x of this)
        yield acc = f(acc, x);
    return acc;
};
IteratorPrototype.reduce = function(f, acc) {
    for (var x of this)
        acc = f(acc, x);
    return acc;
};

These should suffice for the start, and most common use cases. A proper library will extend this to generators so that values are passed through appropriately, and also will deal with the problem that iterators can be used only once before they are exhausted (in contrast to arrays).

Leave a Comment