Skip to content

Instantly share code, notes, and snippets.

@dherman
Created July 29, 2012 01:44
Show Gist options
  • Save dherman/3195647 to your computer and use it in GitHub Desktop.
Save dherman/3195647 to your computer and use it in GitHub Desktop.
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);
Copy link

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