Created
March 7, 2016 18:45
-
-
Save timotgl/8eba8203ba1746bf727e to your computer and use it in GitHub Desktop.
curryAndCall as a prototype method for Functions
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
Function.prototype.curryAndCall = function () { | |
var args = Array.prototype.slice.call(arguments); | |
var curry = function (originalFunc, collectedArgs) { | |
return function () { | |
var args = Array.prototype.slice.call(arguments); | |
if (args.length + collectedArgs.length >= originalFunc.length) { | |
return originalFunc.apply(originalFunc, collectedArgs.concat(args)); | |
} else { | |
return curry(originalFunc, collectedArgs.concat(args)); | |
} | |
} | |
}; | |
if (args.length >= this.length) { | |
return this.apply(this, args); | |
} else { | |
return curry(this, args); | |
} | |
}; | |
// Test subject: function with 4 arguments. | |
var logFour = function (a, b, c, d) { | |
console.log('--------->', a, b, c, d); | |
}; | |
// Keep pre-populating arguments for logFour() until we have all four, | |
// then call the original function with all collected arguments. | |
logFour.curryAndCall(1)(2,3)(4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://gist.github.com/alexdiliberto/2a516eeea9a4d9eb52e2 but I tried to avoid using additional helper functions.