kingjs/enumerable.define
@Defines a function that returns an Enumerable.
Usage
Define an Enumerable
that generates a finite number of clock ticks and then use it to generate 3 ticks like this:
var define = require('@kingjs/enumerable.define');
var currentTicks = define(
function generatorFactory(tickCount) {
return function generator() {
if (tickCount <= 0)
return false;
tickCount--;
// ensure at a tick elapses between generations
if (this.current_) {
while (this.current_ == Date.now())
;
}
this.current_ = Date.now();
return true;
}
}
);
var enumerable = currentTicks(3);
var enumerator = enumerable.getEnumerator();
var result = [];
while (enumerator.moveNext())
result.push(enumerator.current);
result;
Result is something like this:
[
1534412527360,
1534412527361,
1534412527362
]
Enumerable
& Enumerator
Interfaces declare interface Enumerable {
getEnumerator(): Enumerator
}
declare interface Enumerator {
moveNext(): boolean,
current
}
An Enumerable
is a sequence of lazily generated values. To enumerate the values in an Enumerable
, first call getEnumerator
to get an Enumerator
, and then call moveNext
on the Enumerator
.
If moveNext
returns true
, then a value has been generated and can be accessed via current
. Subsequent calls to moveNext
which return true
generate subsequent values which can be accessed via current
.
If moveNext
returns false
, then all values have been generated and current
returns undefined
. At this point subsequent calls to moveNext
will continue to return false
and current
will continue to return undefined
.
API
declare function define(
generatorFactory: (...args: any[]) =>
(this: { current_ }) => boolean
): (...args: any[]) => Enumerable
Parameters
-
generatorFactory
: A function that returns agenerator
function closed overargs
. The functiongenerator
is called whenmoveNext
is called and should either assign a freshly generated value tothis.current_
and returntrue
or, if no more values remain to be generated, returnfalse
.
Return Value
Returns a function which takes arbitrary parameters args
and returns an Enumerable
whose values are generated by calls to a generator
created by generatorFactory
using args
.
Remarks
A generator
may assume that after it returns false
the scaffolding:
- Will set
this.current_
toundefined
. - Will prevent subsequent invocations.
The generatorFactory
will be invoked upon the first call to moveNext
with the this
and the arguments
passed to the function returned by define
.
More Remarks
Enumerator
is similar in functionality to Javascript's Iterator
pattern but is more memory efficient. Iterator
requires creation of a wrapper object (e.g. { value: 'someGeneratedValue' }
) for every generated value but Enumerable
returns the value directly from current
.
Install
With npm installed, run
$ npm install @kingjs/enumerable.define
Acknowledgments
Like the boilerplate types generated by C# yield
syntax.
License
MIT