generator's .map(..) now supports a generator as handler...

Signed-off-by: Alex A. Naanou <alex.nanou@gmail.com>
This commit is contained in:
Alex A. Naanou 2021-05-18 02:07:08 +03:00
parent b80c0611a6
commit 6aea814138
3 changed files with 37 additions and 4 deletions

View File

@ -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()
```
<!--
XXX .reduce(..) can return a non-iterable -- test and document this case...
...compare with Array.prototype.reduce(..)
@ -1865,6 +1877,11 @@ but returning a reusable `<Generator>`.
#### `<Generator>.map(..)` / `<Generator>.filter(..)` / `<Generator>.reduce(..)` / `<Generator>.flat()`
Counterparts to `<generator>`'s
[`.map(..)` and friends](#generatormap--generatorfilter--generatorreduce) and
[`.flat(..)`](#generatorflat)
but return a `<Generator>`.
<!-- XXX -->

View File

@ -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(){

View File

@ -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": {