Last active
August 29, 2015 14:25
-
-
Save AGhost-7/1b86220a5166585e67b9 to your computer and use it in GitHub Desktop.
Function Piping in Javascript
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
> 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 |
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
// 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