Skip to content

Instantly share code, notes, and snippets.

@davidaurelio
Created April 30, 2013 10:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidaurelio/5487842 to your computer and use it in GitHub Desktop.
Save davidaurelio/5487842 to your computer and use it in GitHub Desktop.
Simple higher-order partial function that takes advantage of sparse arrays to make parameters skippable.
function partial(fn, fixedArgs) {
return function() {
var args = fixedArgs.slice(), skipped = 0;
for (var i = 0, n = arguments.length; i < n; i++) {
while (i + skipped in args) { skipped++; }
args[i + skipped] = arguments[i];
}
return fn.apply(this, args);
};
}
function f(a, b, c, d, e, f) { return [a, b, c, d, e, f] };
var fʹ = partial(f, [, 2, , 4, , 6]);
fʹ(1, 3, 5); // [1, 2, 3, 4, 5, 6]
var fʺ = partial(f, [1, 2, , , 5]);
fʺ(3, 4, 6); // [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment