Skip to content

Instantly share code, notes, and snippets.

@Bclayson
Created April 7, 2016 21:52
Show Gist options
  • Save Bclayson/21c93b34161b569f36053195f9d29671 to your computer and use it in GitHub Desktop.
Save Bclayson/21c93b34161b569f36053195f9d29671 to your computer and use it in GitHub Desktop.
Compose function decorator that takes data and subsequent functions and returns a function that composes callbacks right to left. Uses "pipe" function from pipe.js (my gist) and Underscore.js
var nums = [1, 2, 3, 4, 5];
function sum(numList) {
return numList.reduce(function(memo, num) {
return memo + num
}, 0)
}
function double(num) {
return num * 2
}
function square(num) {
return num * num
}
function cons(newItem, coll) {
return [newItem].concat(coll)
}
function pipe() {
var data = _.first(arguments);
var fns = _.rest(arguments);
var fn = _.first(fns);
if (!_.isUndefined(fn)) {
var newData = fn(data)
return pipe.apply(this, cons(newData, _.rest(fns)))
}
return data
}
function compose() {
var fns = _.toArray(arguments);
return function(data) {
return pipe.apply(this, cons(data, fns))
}
}
var sumDoubleSquareList = compose(sum, double, square);
console.log(sumDoubleSquareList(nums));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment