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
// http://jsfiddle.net/wpYeW/1/ | |
// readable is a function(Writable writable, Boolean isClosed) | |
// writable is a function(Object chunk, Readable readable) | |
// duplex is a function(Readable readable) -> Readable | |
function createReadArray(list) { | |
var i = 0; | |
return function readable(writable, isClosed) { | |
if (isClosed) return | |
if (i === list.length) return writable(null) | |
writable(list[i++], readable) | |
} | |
} | |
function createLogger() { | |
return function writable(chunk, readable) { | |
console.log("chunk", chunk) | |
if (readable) readable(writable) | |
} | |
} | |
var double = map(function (i) { return i * 2 }) | |
var square = map(function (i) { return i * i }) | |
var logger = createLogger() | |
square(double(createReadArray([1, 2, 3])))(logger) | |
pipe(createReadArray([1, 2, 3])) | |
.pipe(double) | |
.pipe(square) | |
(logger) | |
// pipe takes a readable source and adds a pipe method | |
// which can be called with a duplex and it will return | |
// a new readable from the duplex which also has pipe method! | |
function pipe(readable) { | |
readable.pipe = function (duplex) { | |
return pipe(duplex(readable)) | |
} | |
return readable | |
} | |
// map Duplex : Lambda -> Readable -> Readable | |
function map(lambda) { | |
// duplex is Readable -> Readable | |
return function duplex(source) { | |
// source is Readable | |
return function readable(destination, isClosed) { | |
// destination is a Writable | |
source(function writable(chunk) { | |
chunk === null ? destination(null) : | |
chunk instanceof Error ? destination(chunk) : | |
destination(lambda(chunk), readable) | |
}, isClosed) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment