@kingjs/define-generator
Define a generator given a MoveNext()
factory; Poor man's yield
.
Usage
Yield each argument passed to a function like this:
var defineGenerator = require('@kingjs/define-generator');
var sequence = defineGenerator(
function moveNextFactory() {
var array = arguments;
var index = -1;
return function moveNext() {
if (index + 1 == array.length)
return false;
this.current_ = array[++index];
return true;
}
}
);
Voila! Now, test sequence
like this:
var enumerator = sequence(0, 1, 2);
var enumerator = enumerable.getEnumerator();
var actual = [];
while (enumerator.moveNext())
actual.push(enumerator.current);
actual;
outputs:
[0, 1, 2];
API
declare function defineGenerator(
moveNextFactory: (...args: any[]) => {
moveNext: () => boolean
}
): {
getEnumerator: () => {
moveNext: () => boolean,
current: any
}
}
Parameters
moveNextFactory
: A function that returns amoveNext()
function closed over the arguments passed to the generator.
Return Value
An enumerable that uses a
moveNext()
created by calling themoveNextFactory()
with the arguments passed to the generator.
Remarks
With first class compiler yield
support the above example could simply be:
function sequence() {
for (var i = 0; i < arguments; i++)
yield arguments[i];
}
While defineGenerator
does not generate the state machine to track which element is next in line, hence the requirement to provide the moveNextFactory()
, it does generate the type scaffolding, the Enumerable
and Enumerator
, which, given the state machine, returns a similar result.
Only "similar" because the official JavaScript yield
returns an Iterator
interface while defineGenerator
returns an Enumerable
interface ala C#.
One critique of the Iterator
interface is that it creates a new object to wrap the result for every iteration and for termination. For example, an empty sequence requires creation of a { done: true }
object when using Iterator
whereas Enumerable
simply returns false
from moveNext()
.
Install
With npm installed, run
$ npm install @kingjs/define-generator
Acknowledgments
define-generator
was inspired by the boilerplate generated by C# yield
syntax.
See Also
License
MIT