Created
June 13, 2015 05:43
-
-
Save Gwash3189/4a9d450ea5b35dea56d8 to your computer and use it in GitHub Desktop.
call a function curried instead of normally
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
Function.prototype.curry = function(){ | |
var length = getParamNames(this); //get arguments length | |
if(arguments.length === length){ //if all the arguments are provided | |
return this.apply(null, arguments); //call itself with the provided arguments | |
} else { // if not enough arguments provided | |
var outterArgs = argumentsToArray(arguments); //convert the argument 'array-like object' into a real array | |
return cacheOutterArguments(outterArgs, this); //cache the arguments in a function, | |
//pass original 'this' and return a new function | |
} | |
function cacheOutterArguments(outterArgsArray, self){ | |
//use closure to cache outter arguments | |
return function(){ | |
// concat the previous arguments and next arguments togeather | |
var bothArgsArray = outterArgsArray.concat(argumentsToArray(arguments)); | |
//recursevly call the same function, with the same 'this' as before and the new arguments | |
return Function.prototype.curry.apply(self, bothArgsArray); | |
}; | |
} | |
function getParamNames(func) { // original source http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript | |
var ARGUMENT_NAMES = /([^\s,]+)/g; //this will isolate the argument names | |
//getting the argument names back in an array will allow us to track how many arguments the function takes | |
var fnStr = func.toString(); | |
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); | |
if(result === null){ | |
result = []; | |
} | |
return result.length; | |
} | |
function argumentsToArray(args) { | |
var argArray = []; | |
for(var i = 0; i < args.length; i++){ | |
argArray.push(args[i]); | |
} | |
return argArray; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment