Last active
August 12, 2019 19:34
-
-
Save kalisjoshua/40b639edfb62b9156292a95fd70974fb to your computer and use it in GitHub Desktop.
Simple utility function for "pipe-ing" values into functions because JavaScript doesn't have a Pipe (forward) operator... yet.
This file contains hidden or 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
// Utility Function Definition | |
// A pipeline will call a series of functions pipe-ing output to input. | |
function pipe () { | |
return [].slice.call(arguments) | |
.reduce(function (acc, fn) { | |
return fn(acc) | |
}) | |
} | |
// The above code compresses better then the ES2015 version. | |
// const pipe = (...arg) => args.reduce((acc, fn) => fn(acc)) | |
// ... not to mention, this doesn't as gracefully accept multiple arguments | |
// e.g. pipe([1, 2, 3], fn, fn, fn) | |
// Example | |
const result = pipe( | |
[1, 2, 3, 4, 5, 6], | |
(args) => args.reduce((a, b) => a + b), | |
(result) => result * 2, | |
addWord('is the answer to the ultimate question of'), | |
addWord('Life'), | |
addWord(', The Universe'), | |
addWord('and Everything.'), | |
) | |
// result = '42 is the answer to the ultimate question of Life , The Universe and Everything.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment