Last active
August 29, 2015 14:09
-
-
Save shawndumas/e288a997ceffcfaecbe3 to your computer and use it in GitHub Desktop.
Partial Application with Substitution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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