Skip to content

Instantly share code, notes, and snippets.

@hoodwink73
Last active July 5, 2018 04:48
Show Gist options
  • Save hoodwink73/03596e963f2600df5892f220e5bedf9c to your computer and use it in GitHub Desktop.
Save hoodwink73/03596e963f2600df5892f220e5bedf9c to your computer and use it in GitHub Desktop.
Basic functional programming concepts taken from the course Functional Light v2 by Kyle Simpson on Frontend Masters

Instructions

  1. Define a compose(..) that takes any number of functions (as individual arguments) and composes them right-to-left.

  2. Define a pipe(..) that takes any number of functions (as individual arguments) and composes them left-to-right.

function increment(x) { return x + 1; }
function decrement(x) { return x - 1; }
function double(x) { return x * 2; }
function half(x) { return x / 2; }
function compose(...fns) {
return function composed(result) {
for (var i = fns.length-1; i>=0; i--) {
result = fns[i](result);
}
return result;
};
}
function pipe(...fns) {
return function piped(result) {
for (var i = 0; i < fns.length; i++) {
result = fns[i](result);
}
return result;
};
}
var f = compose(decrement,double,increment,half);
var p = pipe(half,increment,double,decrement);
f(3) === 4;
// true
f(3) === p(3);
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment