Skip to content

Instantly share code, notes, and snippets.

@josherich
Last active January 4, 2016 03:09
Show Gist options
  • Save josherich/8559620 to your computer and use it in GitHub Desktop.
Save josherich/8559620 to your computer and use it in GitHub Desktop.
Functional Javascript
bind = function(oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
// currying
function curry1(fun) {
return function(arg) {
return fun(arg);
}
}
function curry2(fun) {
return function(arg2) {
return function(arg1) {
return fun(arg1, arg2);
}
}
}
// partially applying
function partial1(fun, arg1) {
var args = construct(arg1, arguments);
return fun.apply(fun, args);
}
function partial2(fun, arg1, arg2) {
var args = concat([arg1, arg2], arguments);
return fun.apply(fun, args);
}
function partialn(fun, ...) {
var pargs = _.rest(arguments);
return function() {
var args = concat(pargs, _.toArray(arguments));
return fun.apply(fun, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment