Skip to content

Instantly share code, notes, and snippets.

@maetl
Created March 25, 2017 12:09
Show Gist options
  • Save maetl/2d973084e703530d9ef18d3f0e5a153f to your computer and use it in GitHub Desktop.
Save maetl/2d973084e703530d9ef18d3f0e5a153f to your computer and use it in GitHub Desktop.
Lazy pipeline API using wrapped iterators and generators to pump values through the chain
function Pipe(sequence) {
const wrappedIterator = sequence[Symbol.iterator]();
this.next = wrappedIterator.next.bind(wrappedIterator);
}
Pipe.step = function(generator) {
return new Pipe({
[Symbol.iterator]: generator
});
}
Pipe.prototype[Symbol.iterator] = function() {
return this;
}
Pipe.prototype.map = function(fn) {
const sequence = this;
return Pipe.step(function*() {
for (let entry of sequence) {
yield fn(entry);
}
});
}
Pipe.prototype.filter = function(fn) {
const sequence = this;
return Pipe.step(function*() {
for (let entry of sequence) {
if (fn(entry)) yield entry;
}
});
}
Pipe.prototype.take = function(number) {
const sequence = this;
return Pipe.step(function*() {
for (let index=0; index < number; index++) {
yield sequence.next().value;
}
})
}
Pipe.prototype.all = function() {
return [...this];
}
const evenValues = (x) => (x % 2) == 0;
const squareValues = (x) => x * 2;
const filteredPipeline = new Pipe([1,2,3,4]).filter(evenValues);
console.log("expected: 2", `actual: ${filteredPipeline.next().value}`);
console.log("expected: 4", `actual: ${filteredPipeline.next().value}`);
const squareEvenValues = new Pipe([1,2,3,4,5,6,7,8,9]).filter(evenValues).map(squareValues);
console.log("expected: 4,8,12,16", `actual: ${squareEvenValues.all()}`);
const firstTwoSquared = new Pipe([1,2,3,4,5,6]).filter(evenValues).map(squareValues).take(2);
console.log("expected: 4,8", `actual: ${firstTwoSquared.all()}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment