Skip to content

Instantly share code, notes, and snippets.

@leandromoreira
Last active April 27, 2016 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandromoreira/3beb87e8ed2b4843e8fee42717ad4bbb to your computer and use it in GitHub Desktop.
Save leandromoreira/3beb87e8ed2b4843e8fee42717ad4bbb to your computer and use it in GitHub Desktop.
// 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