CURRYING in Javascript

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument.

Currying is a transformation of functions that translates a function from callable an f(a, b, c) into callable an f(a)(b)(c).

Regular function(Not curry)
function notCurry(x, y, z) {
    return x + y + z
}


Curry function

function curry(x) {
  return function (y) {
    return function (z) {
      return x + y + z;
    };
  };
}
curry(10)(20)(30);

the result will be 60.

Short syntax:-

const curry = (x) => (y) => (z) => x + y + z;

Basic example

const curry = (f) => (a) => (b) => f(a, b);
function sum(a, b) {
  return a + b;
}
let curriedSum = curry(sum);
curriedSum(10)(5); // 15

 

Comments

Popular posts from this blog

LeetCode 350: Intersection of Two Arrays II

LeetCode 35: Search Insert Position

LeetCode 217: Contains Duplicate