Skip to content

Instantly share code, notes, and snippets.

@dherman
Created Jul 29, 2012
Embed
What would you like to do?
Function utilities
(function(Fp, Ap) {
var applyMethod = Fp.apply,
bindMethod = Fp.bind,
callMethod = Fp.call;
var sliceMethod = Ap.slice,
concatMethod = Ap.concat;
var apply = callMethod.bind(applyMethod),
bind = callMethod.bind(bindMethod),
call = callMethod.bind(callMethod);
// This is ES5-only. An ES3 shim of Function.prototype.bind won't work.
// It can be implemented in ES3 but I'm starting with just this.
function applyNew(f, args) {
var thunk = apply(bindMethod, f, call(concatMethod, [null], args));
return new thunk();
}
// (this: (this: C, A ...) -> new C, A ...) -> new C
// analog of Function.prototype.call for new
Fp.construct = function construct() {
return applyNew(this, call(sliceMethod, arguments));
};
// (this: (this: C, A ...) -> new C, [A ...]) -> new C
// analog of Function.prototype.apply for new
Fp.assemble = function assemble(args) {
return applyNew(this, args);
};
// (this: (this: A, B ...) -> C) -> (this: _, A, B ...) -> C
// convert the this parameter to the first explicit parameter
Fp.selfless = function selfless() {
var f = this;
return function(self) {
return apply(f, self, call(sliceMethod, arguments, 1));
};
};
// (this: (this: _, A, B ...) -> C) -> (this: A, B ...) -> C
// convert the first explicit parameter to the this-parameter
Fp.selfish = function selfish() {
var f = this;
return function() {
return apply(f, null, call(concatMethod, [this], call(sliceMethod, arguments)));
};
};
})(Function.prototype, Array.prototype);
// selfless:
var hasOwn = Object.prototype.hasOwnProperty.selfless();
console.log(hasOwn({foo:1}, "foo"));
// selfish:
function add1(n) {
return n + 1;
}
Number.prototype.add1 = add1.selfish();
console.log(41..add1());
// construct:
function Thingy() {
this.stuff = arguments;
}
var x = Thingy.construct(1, 2, 3);
console.log(x.stuff);
// assemble:
var y = Thingy.assemble([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
console.log(y.stuff);
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jul 29, 2012

This reminded me of something I made a while ago and left in my scratch folder that's might be kind of useful, inspired me to fix it up enough to be a gist. https://gist.github.com/3195910

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment