DEV Community

sougato Pal
sougato Pal

Posted on

Javascript Currying and partials

Currying and partials have become the common interview questions for Javascript nowadays. These are very important to functional programming. While underlying concepts is common in both of then there are some differences as well

Currying

Currying is pattern in which a function which takes multiple arguments is transformed into series of function which takes one argument and produce the same result.

sum(2,3) is transformed to sum(2)(3)

To achieve this we need to have curry function which takes any function as an argument and transform into a curried function.

Though it may look complex the underlying logic is simple and easy to understand if you know about Javascript closures. We need to compare the number of arguments which is passed to the curried function with that of function signature. As long as it is lesser than that of function signature, We need to return a closure which will have reference to earlier arguments like this:

function curry(func){
  return function curried(...args){
    if(args.length >= func.length){
       return func.apply(this,args)
    }else{
       return function(...args2){
         return curried.apply(this,args.concat(args2))
       }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
function sum(a, b, c){return a+b+c}

sum(1,2,3) //6

let c1 = curry(sum);

c1(1,2,3) //6
c1(1)(2)(3)  //6

Enter fullscreen mode Exit fullscreen mode

Partials

A partials function takes a function and return a function which takes fewer arguments.Some arguments are kind of attached to it internally. This is also implemented through closures and are similar to currying

Lets us assume we have function which multiply two number

function multiply(a,b){return a * b}

We can use the multiply function to create a Square of a number.

function createSquarePartial(fn){
  return function(args){
    return fn(args,args)
  }
}
Enter fullscreen mode Exit fullscreen mode

We can then use it to transform the multiply function to take a single argument and return the square of it.

var getSquare = createSquarePartial(multiply)
getSquare(5) // 25
Enter fullscreen mode Exit fullscreen mode

Thus we can see getSquare takes a single argument and return the square of the number using the multiply function.

Top comments (0)