Last active
December 15, 2015 02:19
-
-
Save eeroan/5186187 to your computer and use it in GitHub Desktop.
Awesome partial application function for JavaScript
This file contains 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 __ = {} | |
function papply(func, givenArguments) { | |
var indexOf = givenArguments.indexOf(__) | |
var givenArgsSize = givenArguments.length | |
var requiredArgsSize = func.length | |
if(givenArgsSize >= requiredArgsSize && (indexOf < 0 || indexOf >= requiredArgsSize)) | |
return func.apply(func, givenArguments) | |
else | |
return function() { | |
return (function(givenArguments, remainingArguments) { | |
for(var i = 0; i < givenArguments.length; i++) | |
if(givenArguments[i] === __) givenArguments[i] = remainingArguments.shift() | |
return papply(func, givenArguments.concat(remainingArguments)) | |
})(givenArguments.slice(0), Array.prototype.slice.call(arguments)) | |
} | |
} | |
Function.prototype.papply = function() { | |
return papply(this, Array.prototype.slice.call(arguments)) | |
} | |
//EXAMPLE | |
function sum(a, b, c, d) { return a + b + c + d} | |
//All following examples return 'abcd' | |
sum.papply('a', 'b', 'c', 'd') | |
sum.papply('a', 'b')('c', 'd') | |
var ab = sum.papply('a', 'b') | |
ab('c','d') | |
ab('c','d') | |
ab('c')('d') | |
sum.papply('a', __, 'c', __)('b','d') | |
sum.papply('a', __, 'c', __)('b')('d') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment