Created
March 1, 2016 23:42
-
-
Save timReynolds/41f3c7c62567408da88b to your computer and use it in GitHub Desktop.
Compose example
This file contains 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 consoleLine = "<p class=\"console-line\"></p>"; | |
console = { | |
log: function (text) { | |
$("#console-log").append($(consoleLine).html(text)); | |
} | |
}; | |
// New function called compose | |
// works from right to left | |
var compose = function(f, g) { | |
return function(x) { | |
return f(g(x)); | |
}; | |
}; | |
function curry(func) { | |
var requiredArgs = func.length; | |
return function curried() { | |
var args = Array.prototype.slice.call(arguments, 0); | |
if (args.length >= requiredArgs) { | |
return func.apply(null, args); | |
} | |
return function() { | |
var args2 = Array.prototype.slice.call(arguments, 0); | |
return curried.apply(null, args.concat(args2)); | |
}; | |
}; | |
} | |
var multiply = curry(function(x,y) { | |
return x * y; | |
}); | |
var append = curry(function(x,y) { | |
return y+x; | |
}); | |
const multiplyBy100 = multiply(100); | |
const formatAsPercent = append('%'); | |
const commision = 0.05; | |
const commisionAsPercentage = compose(formatAsPercent, multiplyBy100); | |
console.log(commisionAsPercentage(commision)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment