JS: Function Currying with ‘Bind’
Tutorialspoint defines Currying as a technique of evaluating function with multiple arguments, into sequence of functions with single argument.
Currying is one of the most commonly asked questions during the interviews.
A common problem usually give during interviews is to find the sum of numbers using function currying:
sum(50)('*')............................// returns 50
sum(50)(40)('*')....................... // returns 90
sum(50)(40)(30)('*')................... // returns 120
sum(50)(40)(30)(20)('*')............... // returns 140Keep on adding the argument till `*` is encountered
As usual, the approach which quickly came to my mind was to solve this by using ‘Closures’. I can create a closure that will hold the total values till ‘*’ is received. Once ‘*’ is passed, return the total sum.
Thus, my solution was:
// I'm just using happy cases and no negative validations.const sum = function(number) {
let total = number;
let curry = (arg) => {
if (arg === '*') {
return total
};
total = total + arg;
return curry;
}
return curry;
}
The solution works fine and it gets the job done. However, now the idea was to achieve the same without using a Closure.
“Bind” to the rescue
we can take help from bind to achieve the same without any closure.
Bind takes the first argument as context, and after that ’n’ arguments can be passed that serves as default arguments.
So, instead of returning a curry function, we will return the parent method itself binding it to a ‘total’ value that will give us the result.
// I'm just using happy cases and no negative validations.let sum = function (x) {
let total = arguments[0];
if(arguments.length === 1 && arguments[0] === '*'){
return 0;
}
if(arguments.length === 2){
if(arguments[1] === '*'){
return arguments[0];
}
total = arguments[0] + arguments[1];
}
return sum.bind({}, total);
}
Here, at each call, a new method is being returned bound with an argument that holds the cumulative of all the previous calls. when ‘*’ is encountered the actual value is returned.