Last active
August 29, 2015 14:10
-
-
Save reu/f6126685e1138710afd8 to your computer and use it in GitHub Desktop.
Some building blocks for functional programming in Javascript
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
function curry(fn) { | |
var arity = fn.length, | |
args = Array.prototype.slice.call(arguments, 1); | |
function accumulator() { | |
var leftArgs = args.concat(Array.prototype.slice.call(arguments, 0)); | |
if (leftArgs.length >= arity) { | |
return fn.apply(this, leftArgs); | |
} else { | |
return curry.apply(this, [fn].concat(leftArgs)); | |
} | |
} | |
return args.length >= arity ? accumulator() : accumulator; | |
} | |
function compose() { | |
var fns = Array.prototype.slice.call(arguments); | |
return fns.reduce(function(f, g) { | |
return function() { | |
return f(g.apply(this, arguments)); | |
} | |
}); | |
} |
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 assert = console.assert; | |
var sum = function(a, b, c) { return a + b + c } | |
var curriedSum = curry(sum); | |
assert(sum(1, 2, 3) == curriedSum(1)(2)(3), "Curring all arguments"); | |
assert(sum(1, 2, 3) == curriedSum(1, 2)(3), "Curring half arguments"); | |
assert(sum(1, 2, 3) == curriedSum(1, 2, 3), "No curring"); | |
var downcase = function(string) { return string.toLowerCase() } | |
var removeNumbers = function(string) { return string.replace(/\d/g, "") } | |
var removeSpaces = function(string) { return string.replace(/\s/g, "") } | |
var name = "R0Dr1G0 N4V4rR0"; | |
assert(compose(downcase, removeNumbers, removeSpaces)(name) == "rdrgnvrr", "Composing three function") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment