Desugared generator constructor
Library lets you create ES6 generators with in the (dis)comfort of ES5 JS environment (like < email@example.com) and without syntax sugar. This magic happens at the cost of the syntax transformations at the generator instantiation. You can use this with task.js, co, suspend or any other Generator-based flow control based library without waiting on your favorite JS environment to enable generators for you!
Given a generators support in your environment you should be able to write code like this:
varstep = step || 1var n = fromwhile n <= toyield nn ++return nvar digits = range0 9var stepwhile step = digitsnext !stepdoneconsole.logstepvalue
Unfortunately above code will throw a syntax error in engines that don't have generators support.
With a degenerate you can create equivalent range generator by typeing this:
var Generator = require"degenerate"var range =step = step || 1var n = fromwhile n <= toyieldnn ++return nvar digits = range0 9var stepwhile step = digitsnext !stepdoneconsole.logstepvalue
Notice the difference ? Just loose a
* and replace
yield n statement with
yield(n) call expression.
You can also use delegeting yields:
var concat =yield* xsyield* ysvar zs = concatrange1 3 range4 7while step = zsnext !stepdoneconsole.logstepvalue
Don't try to outsmart this tool, even though
yield may feel like a first class function, it is not and any attempts to use it as such will break the code.
If you try to define function that refers to
yield in strict mode, you'll get a syntax error :( To overcome this limitation all you need to do is write
"use strict";var range = Generatorwhile from <= tothisyieldfrom++var concat =thisyield* xsthisyield* ys
This is the most unfortunate limitation of all! You can not enclose any scope variables, all that generator body will have has access to is a top scope or whatever has being passed into as
this pseudo variable or as arguments.
Generator function parses source of the given function, transforms AST to make function expression a generator, replace
yield x. Transforms new AST via facebook/regenerator (Thank them for making it possible) and finally generates a generator from the results.
npm install degenerate