Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Last active August 29, 2015 14:25
Show Gist options
  • Save AGhost-7/1b86220a5166585e67b9 to your computer and use it in GitHub Desktop.
Save AGhost-7/1b86220a5166585e67b9 to your computer and use it in GitHub Desktop.
Function Piping in Javascript
> var pipe = require('./pipe')
undefined
> var spread = pipe.spread
undefined
> function upper(s) { return s.toUpperCase() }
undefined
> pipe('foo',upper)
'FOO'
> function splitter(sp) { return function(str) { return str.split(sp) } }
undefined
> pipe('foo', upper, splitter(''))
[ 'F', 'O', 'O' ]
> function printArgs() { console.log(arguments) }
undefined
> pipe('foo', upper, splitter(''), spread(printArgs))
{ '0': 'F', '1': 'O', '2': 'O' }
undefined
// To be used with pipe. Will take the array which was accumulated and instead to the function arguments,
// versus being passed into the function as an array.
function spread(fn){
return {
call: function(th, accu){
return fn.apply(th, accu);
}
}
}
// Start with a base value and run it through all functions.
function pipe(base){
return Array.prototype.slice.call(arguments, 1).reduce(function(accu, fn){
return fn.call(undefined, accu);
}, base);
}
pipe.spread = spread;
module.exports = pipe;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment