Sunny Gupta
Sunny Gupta: iCodeStartups

Follow

Sunny Gupta: iCodeStartups

Follow

Currying in JS.

Sunny Gupta's photo
Sunny Gupta
·Nov 2, 2017·

1 min read

I would define currying as invoking a function with fewer arguments than the function expects. This returns a new function that can be called with the remaining arguments. You could also invoke it with lower than remaining arguments and it would return yet another function.

Sounds confusing? Let’s look at the expected behaviour of our curry function:

const add = (a,b,c,d)=>{return a+b+c+d}

let add2 = curry(add,2);
//Here add2 is the curried function. We can use it like:

add2(3,4,5) //results in 14 (2+3+4+5)
//or
add2(3,4)(5) //Same result
//or
add2(3)(4)(5) //Same result

//This works too -
const add2_3 = add2(3)
//The above will now accept two more arguments.

add2_3(4,5) //results in 14 too.

How would you go about implementing this?

 
Share this