Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Last active August 29, 2015 14:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawndumas/e288a997ceffcfaecbe3 to your computer and use it in GitHub Desktop.
Save shawndumas/e288a997ceffcfaecbe3 to your computer and use it in GitHub Desktop.
Partial Application with Substitution
var partial = function () {
var toArray = function (a) { return [].slice.call(a); },
appliedArgs = toArray(arguments),
fn = appliedArgs.shift(),
placeholderPositions = appliedArgs.map(function (e, i) {
if (e === '_') { return i; }
}).join('').split('');
return function () {
var args = toArray(arguments);
placeholderPositions.forEach(function (i) { appliedArgs[i] = args.shift(); });
appliedArgs.concat(args);
args.reduce(function (p, c) {
return p.push(c);
}, appliedArgs);
return fn.apply(null, appliedArgs);
};
};
var two = function (a, b, c) { console.log(JSON.stringify(arguments, null, 2)); };
var one = partial(two, '_', 'this should be b');
one('this should be a');
/*
{
"0": "this should be a",
"1": "this should be b"
}
*/
var three = function (a, b, c) { console.log(JSON.stringify(arguments, null, 2)); };
var one = partial(three, 'this should be a', '_', 'this should be c');
one('this should be b');
/*
{
"0": "this should be a",
"1": "this should be b",
"2": "this should be c"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment