Skip to content

Instantly share code, notes, and snippets.

@Raynos

Raynos/x.js Secret

Last active December 15, 2015 07:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Raynos/ff142ba21f9790d418d1 to your computer and use it in GitHub Desktop.
// 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