In general, generators are very hard to polyfill. (Not impossible, as
you can do a CPS transform of the source code, but very difficult.)
It depends on what you want. For concise specification of iteration,
you can do something without full CPS transform, by using monadic
coding style. My scratch area for monadic generators and promises:
monadic javascript/typescript: promises and generators
https://gist.github.com/clausreinke/5984869
(which you can run with TypeScript 0.9, playground or npm)
Given that JS control-structures aren't predefined but built-in, we can't
redefine them but have to define our own, but it still isn't too bad. For
instance, the simple generator example
https://gist.github.com/clausreinke/5984869#file-monadic-ts-L492-L506
outputs
// Generator.forIn, with yield, plain iteration (prefix #)
# yield1 1
(yield1 returns 0)
# yield2 1
(yield2 returns 1)
# yield1 2
(yield1 returns 2)
# yield2 4
(yield2 returns 3)
# yield1 3
(yield1 returns 4)
# yield2 9
(yield2 returns 5)
# 1,2,3
Note from the iteration loop that I've implemented a functional API
(next returns {done,value,next}) instead of an imperative one (next
returns {done,value} and modifies its host).
The standard recursive tree generator
https://gist.github.com/clausreinke/5984869#file-monadic-ts-L521-L529
even looks readable without special syntax
function iterTree(tree) {
return Array.isArray(tree)
? tree.map( iterTree ).reduce( (x,y)=> x.then( _=> y ),
G.of(undefined) )
: G.yield(tree);
}
var generator3 = iterTree([1,[],[[2,3],4],5]);
MonadId.forOf( generator3, y=> (console.log("* "+y), MonadId.of(y)) );
and outputs
// MonadId.forOf, iterTree recursive generator() (prefix *)
* 1
* 2
* 3
* 4
* 5
With a very little syntactic sugar for monads (monad comprehensions,
monadic do notation), it could even be made to look like conventional
code. This has come up several times here, and would have a very high
value for very small cost, if done right.
Claus
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss