diff --git a/README.md b/README.md index bb5438f..0edb385 100644 --- a/README.md +++ b/README.md @@ -1639,6 +1639,18 @@ are yielded down the generator chain. Equivalents to `Array`'s `.map(..)`, `.filter(..)` and `.reduce(..)` but return generators that yield the handler return values. +Note that `.map(..)` here also supports a generator as a handler +```javascript +var expand = function*(n){ + yield* (new Array(n)).fill(n) } + +// will create: [1, 2, 2, 3, 3, 3] +var L = [1,2,3] + .iter() + .map(expand) + .toArray() +``` + diff --git a/generator.js b/generator.js index 72ce7b4..2518d37 100644 --- a/generator.js +++ b/generator.js @@ -93,11 +93,21 @@ module.iter = // Helpers... // XXX this needs to be of the correct type... (???) +// XXX need to accept generators as handlers... var makeGenerator = function(name){ return function(...args){ var that = this return Object.assign( function*(){ + // XXX need to accept generator as handler (i.e. args[0] instanceof Generator)... + /*/ XXX EXPERIMENTAL... + if(args[0] instanceof Generator){ + yield* that(...arguments)[name](...args) + .map(function(g){ + return [...g] }) + .flat() + return } + //*/ yield* that(...arguments)[name](...args) }, { toString: function(){ return [ @@ -227,10 +237,16 @@ object.Mixin('GeneratorProtoMixin', 'soft', { } else { yield e } } }, + // NOTE: if func is instanceof Generator then it's result (iterator) + // will be expanded... map: function*(func){ var i = 0 - for(var e of this){ - yield func(e, i++, this) } }, + if(func instanceof Generator){ + for(var e of this){ + yield* func(e, i++, this) } + } else { + for(var e of this){ + yield func(e, i++, this) } } }, filter: function*(func){ var i = 0 for(var e of this){ @@ -239,7 +255,7 @@ object.Mixin('GeneratorProtoMixin', 'soft', { reduce: function*(func, res){ var i = 0 for(var e of this){ - res = func(res, e, i++, this) } + res = func(res, e, i++, this) } yield res }, pop: function(){ diff --git a/package.json b/package.json index 88853b0..0f94a81 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ig-types", - "version": "6.1.0", + "version": "6.2.0", "description": "Generic JavaScript types and type extensions...", "main": "main.js", "scripts": {