Create a gist now

Instantly share code, notes, and snippets.

@eeroan / papply.js
Last active Dec 15, 2015

What would you like to do?
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