Skip to content

Instantly share code, notes, and snippets.

@laurentjacob
Last active August 1, 2018 19:21
Show Gist options
  • Save laurentjacob/db1df73d5a3e8e66b749d70f66a11f1e to your computer and use it in GitHub Desktop.
Save laurentjacob/db1df73d5a3e8e66b749d70f66a11f1e to your computer and use it in GitHub Desktop.
Code for partialApply blog post
function add (x, y, z) {
return x + y + z;
}
partialApply(add, 1)(1)(2); // yields 4
partialApply(add)(1)(1)(2); // yields 4
partialApply(add)(1, 1)(2); // yields 4
partialApply(add, 1, 1, 2); // yields 4
add.partialApply(1)(1)(2); // yields 4
add.partialApply(1, 1)(2); // yields 4
add.partialApply(1, 1, 2); // yields 4
Function.prototype.partialApply = function() {
var fn = this;
var slice = Array.prototype.slice;
var curr_args = slice.call(arguments);
if(fn.length > curr_args.length) {
return function () {
var new_args = slice.call(arguments);
var args = curr_args.concat(new_args);
return fn.partialApply.apply(fn, args);
}
}
else {
return fn.apply(null, curr_args);
}
};
return fn.partialApply.apply(fn, args);
return fn.partialApply.apply(null, args);
var add = function(x, y, z) {
return x + y + z;
}.partialApply();
var a = add(1, 2, 3); // yields 6
var b = add(1)(2)(3); // yields 6
var c = add(1)(2, 3); // yields 6
var partialAdd = add(1); // yields a function that needs 2 more arguments
var result = partialAdd(2, 3); // yields 6
add(1, 2, 3); // yields 6
add(1)(2)(3); // yields 6
function schonfinkelize(fn) {
var slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
return function () {
var new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
};
}
var addSecondHalf = schonfinkelize(add, 1); // yields a function
addSecondHalf(2, 3); // yields 6
schonfinkelize(add, 1)(2)(3); // Doesn't work
schonfinkelize(schonfinkelize(add, 1)(2))(3); // yields 6
add.length // yields 3
function partialApply(fn) {
var slice = Array.prototype.slice;
var curr_args = slice.call(arguments, 1);
if(fn.length > curr_args.length) {
return function() {
var new_args = slice.call(arguments);
var args = curr_args.concat(new_args);
return partialApply.apply(null, [fn].concat(args));
}
}
else {
return fn.apply(null, curr_args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment