Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Last active March 12, 2017 15:37
Show Gist options
  • Save YozhEzhi/fb8e25d93d160f92fedb8fbdb3b1a14d to your computer and use it in GitHub Desktop.
Save YozhEzhi/fb8e25d93d160f92fedb8fbdb3b1a14d to your computer and use it in GitHub Desktop.
Pipeline & compose functions
/* 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