Created
April 7, 2016 21:52
-
-
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
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
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