Skip to content

Instantly share code, notes, and snippets.

@webbower
Created August 19, 2014 23:34
Show Gist options
  • Save webbower/1aca22868f4e9a5913a3 to your computer and use it in GitHub Desktop.
Save webbower/1aca22868f4e9a5913a3 to your computer and use it in GitHub Desktop.
Functional combinators and composition helpers
// Requires utils.list.js for toList(), first(), and rest()
function tap(callback, val) {
callback(val);
return val;
}
function flip(fn) {
return function() {
return fn.apply(this, toList(arguments).reverse());
};
}
function partial(fn, args) {
if (arguments.length > 2 && !Array.isArray(args) && !isArguments(args)) {
return partial(fn, rest(arguments));
}
if (!args.length) return fn;
else return partial(fn.bind(fn, first(args)), rest(args));
}
function curry(fn, arity) {
if (!isFunction(fn)) {
throw new TypeError('curry() expects first argument to be a function. ' + (typeof fn) + ' given.');
}
arity = Number(arity || fn.length || 0);
return function() {
if (arguments.length >= arity) return fn.apply(this, arguments);
else return curry(partial(fn, arguments), arity - arguments.length);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment