Skip to content

Instantly share code, notes, and snippets.

@eeroan
Last active December 15, 2015 02:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eeroan/5186187 to your computer and use it in GitHub Desktop.
Save eeroan/5186187 to your computer and use it in GitHub Desktop.
Awesome partial application function for JavaScript
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