Last active
May 23, 2018 16:07
-
-
Save rbrahul/b102e770c12778309aa1c22a8994b144 to your computer and use it in GitHub Desktop.
Curry pattern for Functional Programming in Javascript
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 curry(fn) { | |
| let i = 0; | |
| let countedArg = 0; | |
| let method = function(arg) { | |
| return arg; | |
| }; | |
| let args = []; | |
| while(i< fn.length) { | |
| method = (function(fun) { | |
| return function(...params) { | |
| countedArg += params.length; | |
| args = [...args, ...params]; | |
| if(countedArg === fn.length) { | |
| return fn.apply(null, args) | |
| } | |
| return fun; | |
| }; | |
| })(method); | |
| i++; | |
| } | |
| return method; | |
| } | |
| const curried1 = curry(function(a,b,c){ return a + b + c; }); | |
| console.log('Total 1:'+ curried1(3)(4,5)); | |
| const curried2 = curry(function(a,b,c){ return a + b + c; }); | |
| console.log('Total 2:'+ curried2(1,2,5)); | |
| const pow = curry(function(a,b){ return Math.pow(a,b); }); | |
| console.log('Powered Value:'+ pow(2,2)); | |
| const pow2 = curry(function(a,b){ return Math.pow(a,b); }); | |
| console.log('Powered Value:'+ pow2(2)(2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment