Last active
March 12, 2017 15:37
-
-
Save YozhEzhi/fb8e25d93d160f92fedb8fbdb3b1a14d to your computer and use it in GitHub Desktop.
Pipeline & compose functions
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
/* ES5 version */ | |
function pipeline(seed) { | |
var fns = [].slice.call(arguments, 1); | |
return fns.reduce(function(result, fn) { | |
return fn(result); | |
}, seed); | |
} | |
function compose() { | |
var fns = [].slice.call(arguments, 0); | |
return function(seed) { | |
return fns.reduceRight(function(val, fn) { | |
return fn(val); | |
}, seed); | |
} | |
} | |
/* ES6 version */ | |
const pipeline = (seed, ...fns) => fns.reduce((result, fn) => fn(result), seed); | |
const compose = (...fns) => (seed) => pipeline.apply(seed, [seed, ...fns.reverse()]); | |
/* Pipelines examples */ | |
console.log(pipeline()); // undefined | |
console.log(pipeline(42)); // 42 | |
console.log(pipeline(42, n => -n)); // -42 | |
/* Compose examples */ | |
const greet = (name) => `hi: ${name}`; | |
const exclaim = (statement) => `${statement.toUpperCase()}!`; | |
const welcome = compose(greet, exclaim); | |
console.log(welcome('Yozh')); // 'hi: YOZH!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment