iterator - Why do generators not support map()? -


it seems utterly natural me generators, function arrays, should support basic list operations, map(), filter(), , reduce(). missing something?

i wrote code map , seems simple enough, better have functions embedded in generators:

let fancygen = g => {   let rv = function*() {     (let x of g)        yield x;   }   rv.map = function*(p) {    (let x of g)        yield p(x);   }    return rv; } 

i'm new generators, comments on code welcome. in particular, best way write "the identity generator"?

why generators not support map()?

because it's easy fill in userland implementation. es3 didn't include array iteration methods either, maybe see transformers iterators in es7 :-)

generators, function arrays

no, please stop , distinguish iterators generators:

  • an iterator object .next() method conforms iterator protocol.
  • a generator iterator created generator function (function*). .next() method takes argument result of each yield inside generator function. has .return() , .throw() methods.

you'll interested in iterators, don't pass values next, , don't care end result - for of loops do. can extend them desired methods easily:

var iteratorprototype = object.getprototypeof(object.getprototypeof([][symbol.iterator]())); iteratorprototype.map = function*(f) {     (var x of this)         yield f(x); }; iteratorprototype.filter = function*(p) {     (var x of this)         if (p(x))             yield x; }; iteratorprototype.scan = function*(f, acc) {     (var x of this)         yield acc = f(acc, x);     return acc; }; iteratorprototype.reduce = function(f, acc) {     (var x of this)         acc = f(acc, x);     return acc; }; 

these should suffice start, , common use cases. proper library extend generators values passed through appropriately, , deal problem iterators can used once before exhausted (in contrast arrays).


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -