Created
July 25, 2014 15:08
-
-
Save danielepolencic/015798c7038cc54cb2ff to your computer and use it in GitHub Desktop.
stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Stream () { | |
this.fns = []; | |
} | |
Stream.prototype.push = function (element) { | |
var accumulator = this.fns[0](element); | |
for (var i = 1, len = this.fns.length; i < len; i++) { | |
if (accumulator) { accumulator = this.fns[i](accumulator); } else { break; } | |
} | |
}; | |
Stream.prototype.map = function (fn) { | |
this.fns.push(fn); | |
return this; | |
}; | |
Stream.prototype.filter = function (fn) { | |
this.fns.push(function (value) { | |
return fn(value) ? value : null; | |
}); | |
return this; | |
}; | |
Stream.prototype.onValue = function (fn) { | |
this.fns.push(fn); | |
return this; | |
}; | |
var s = new Stream(); | |
s.map(function (x) { return x + 1; }).filter(function (x) { return !(x % 2); }).onValue(function(x) { | |
console.log('onValue: ', x); | |
}); | |
s.push(1); | |
s.push(2); | |
s.push(3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment