-
-
Save leandromoreira/3beb87e8ed2b4843e8fee42717ad4bbb to your computer and use it in GitHub Desktop.
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
// an ordinary function | |
var sum = function(a, b){return a+b} | |
sum(1, 3) // 4 | |
// a curried version of that sum | |
var curriedSum = function(a){ | |
return function(b){return a+b} | |
} | |
var plusOne = curriedSum(1) // function(b) {return a+b} | |
plusOne(3) // 4 | |
plusOne(1) // 2 -> plusOne is useful outside it's original scope | |
// a simple function to curry any other function | |
// we'll use this in future | |
// DO NOT USE THIS IN PRODUCTION | |
var curry = function(uncurriedFn){ | |
var argumentsCall = [] | |
return function curriedFn(){ | |
var args = Array.prototype.slice.call(arguments) | |
if (args.length > 0) { | |
argumentsCall = argumentsCall.concat(args) | |
if (uncurriedFn.length == argumentsCall.length) { | |
return uncurriedFn.apply(this, argumentsCall) | |
} | |
} | |
return curriedFn | |
} | |
} | |
// an usage example of curry | |
var curriedAjax = curry(function(method, path){ | |
return $.ajax(path, {method: method}) | |
}) | |
var ajaxGET = curriedAjax('GET') | |
var allUsers = ajaxGET('/users') | |
var allStars = ajaxGET('/stars') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment