Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@reu
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/f6126685e1138710afd8 to your computer and use it in GitHub Desktop.
Save reu/f6126685e1138710afd8 to your computer and use it in GitHub Desktop.
Some building blocks for functional programming in Javascript
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));
}
});
}
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