Last active
July 20, 2016 15:10
-
-
Save kavitshah8/0830b173a510fcd495441033db4db015 to your computer and use it in GitHub Desktop.
Currying
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 realSum(a, b) { | |
return a + b; | |
}; | |
console.log(realSum(5, 3)); // 8 | |
var sum5 = curryIt(realSum, 5); | |
console.log(sum5(4)); // 9 | |
var sum3 = curryIt(realSum, 3); | |
console.log(sum3(4)); // 7 |
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 realSum(a, b) { | |
return a + b; | |
}; | |
function sum(a, b) { | |
return b ? | |
realSum(a, b) : | |
function(b) { | |
// This anonymous function has access to variable `a` via closure | |
return realSum(a, b); | |
} | |
} | |
console.log(sum(5, 3)); // 8 | |
var sum5 = sum(5); | |
console.log(sum5(4)); // 9 | |
var sum3 = sum(3); | |
console.log(sum3(4)); // 7 |
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
var curryIt = function(fn) { | |
var fnArgsWhileBeingCurried = Array.prototype.slice.call(arguments, 1); | |
return function() { | |
var fnArgsAfterBeingCurried = Array.prototype.slice.call(arguments, 0); | |
return fn.apply(this, fnArgsWhileBeingCurried.concat(fnArgsAfterBeingCurried)); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment