Why do generators not support map()?

前端 未结 1 1709
Happy的楠姐
Happy的楠姐 2020-11-28 16:26

It seems utterly natural to me that generators, which function very much like Arrays, should support the very basic list operations, like map(), filter()<

相关标签:
1条回答
  • 2020-11-28 16:45

    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).

    0 讨论(0)
提交回复
热议问题