A JavaScript library for creating Iterators, Generators and Continuation methods for Arrays.
A JavaScript library for creating Iterators, Generators and Continuation methods for Arrays.
The Iterator would be a method (getIterator()) that augments the Array data type and would have the following interfaces:
Properties:
Methods:
Usage:
var x = [1, 2, 3, 4, 5, 6, 7],
list = x.getIterator();
while (list.moveNext() {
console.log(list.current);
}
console.log(continuation.outList);
continuation.reset();
console.log(continuation.iterate());
The Generator would be a method (getGenerator(numberOfElements)) that augments any Generator function (by accepting the number of elements to be generated) and would have the following interfaces:
Properties:
Methods:
Usage:
//A generic sequence generator function:
function sequence(z) {
"use strict";
var y = 0;
return function () {
y += z;
return y;
};
}
var a = sequence(1).getGenerator(10);//For generating the first 10 elements (1 through 10)
while(a.moveNext()) {
console.log(a.current);
}
a.nextSet(5);//For generating the next 5 elements (11 through 15)
console.log(a.generate());
For creating continuation methods a context object is provided for qualifying methods. The context object provides the following attributes for creating various useful functions:
Usage:
//Continuation Methods
function unique(context) {
"use strict";
return (context.outList.indexOf(context.current) < 0) ? context.current : null;
}
function square(context) {
"use strict";
return (context.current * context.current);
}
function filter(condition) {
"use strict";
return function (context) {
return condition(context.current) ? context.current : null;
};
}
function even(val) {
"use strict";
return (val % 2 === 0);
}
function skip(count) {
"use strict";
return function (context) {
//console.log(this.index.toString() + " : " + this.current.toString());
return ((context.index % (count + 1)) === 0) ? context.current : null;
};
}
//Test Harness using all of above (iterators, generators and continuation methods)
var x = [1, 2, 3, 200, 1, 2, 3, 200],
continuation = x.getIterator();
console.log(continuation.iterate());
continuation.reset();
while (continuation.moveNext(unique, skip(2))) {
//console.log(continuation.current);
}
console.log(continuation.outList);
function sequence(z) {
"use strict";
var y = 0;
return function () {
y += z;
return y;
};
}
var a = sequence(1).getGenerator(10);
while(a.moveNext(square,skip(1))) {
console.log(a.current);
}
a.nextSet(5);
console.log(a.generate(square));