Skip to content

Instantly share code, notes, and snippets.

@bresson
Last active December 24, 2016 01:59
Show Gist options
  • Save bresson/391246ba376a3849b43d48818586204b to your computer and use it in GitHub Desktop.
Save bresson/391246ba376a3849b43d48818586204b to your computer and use it in GitHub Desktop.
Javascript experiment with functional composition allowing arbitrary number of composed functions through ES6, closure and tail recursion.
// experiment of functional composition
const addOne = a => a + 1;
const double = a => a * 2;
const square = a => a * a;
const lCompose = (...args) => {
const _lCompose = ( acc, ...args ) => {
//base case, return acc
if ( !args.length ) {
console.log('acc', acc)
return acc;
} else {
// recurse, shift ...args and call head(acc)
const [head, ...tail] = args;
return _lCompose ( head(acc), ...tail )
}
}
return (initV) => {
return _lCompose(initV, ...args)
}
}
let trans = lCompose(addOne, double, square);
let m = trans(5, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment