I trying to wrap my head around functional programming in js.
I understand add(3)(5) would be:
function add(x) {
return function(y) {
return x + y;
};
}
How would I change this function so add(3)(5)(7)(8) returns 23 or add(1)(2)(3) returns 6?
you can do something like this.
function add(x) {
return function(y) {
if (y) {
return add(x+y);
}
return x;
};
}
Here, you can call as many times as you want.
add(4)();
add(4)(5)(9)();
add(1)(2)(3)....(n)();
Example link
Without modifying your definition for add
, you would need to chain the calls to add
to be (add(add(add(3)(5))(7)))(8)
.
to clarify, this expression breaks down to:
add(3) //returns a function that adds 3
add(3)(5) //returns 8
add(add(3)(5)) // returns a function that adds 8
(add(add(3)(5)))(7) // returns 15
add ((add(add(3)(5)))(7)) //returns function that adds 15
(add(add(add(3)(5))(7)))(8) //returns 23
Breaking it down even further as @zerkms mentioned (and assigning our function definitions to variables) we can see how the chaining of add
works:
var add3 = add(3) //returns a function that adds 3
add3(5) //returns 8
var add8 = add(add3(5)) // returns a function that adds 8
add8(7) // returns 15
var add15 = add(add8(7)) //returns function that adds 15
add15(8) //returns 23
By chaining, we are adding on to the result of the previous call to add
.
Meaning that if add(3)
returns a function that adds 3 and then you add 5 to that number than you can pass that value, 8, into another call to add
to make another function that adds 8 to it's argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With