Currying In JavaScript

Currying In JavaScript

ยท

1 min read

Currying is the process of converting a function that takes multiple arguments at once into a sequence of function's each with a single argument.

๐—›๐—ผ๐˜„ ๐—ฑ๐—ผ๐—ฒ๐˜€ ๐—ถ๐˜ ๐˜„๐—ผ๐—ฟ๐—ธ?

Let's say you have a function with multiple arguments: sum(a,b,c).

๐—จ๐˜€๐—ถ๐—ป๐—ด ๐—–๐˜‚๐—ฟ๐—ฟ๐˜†๐—ถ๐—ป๐—ด, ๐˜†๐—ผ๐˜‚ ๐˜„๐—ถ๐—น๐—น ๐—ด๐—ฒ๐˜ ๐—ฎ ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐˜€๐˜‚๐—บ๐Ÿฌ(๐—ฎ) ๐˜๐—ต๐—ฎ๐˜ ๐—ฟ๐—ฒ๐˜๐˜‚๐—ฟ๐—ป๐˜€ ๐—ฎ ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐˜€๐˜‚๐—บ๐Ÿญ(๐—ฏ) ๐˜๐—ต๐—ฎ๐˜ ๐—ฟ๐—ฒ๐˜๐˜‚๐—ฟ๐—ป๐˜€ ๐—ฎ ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐˜€๐˜‚๐—บ๐Ÿฎ(๐—ฐ).

๐—œ๐—ป ๐—ฆ๐—ถ๐—บ๐—ฝ๐—น๐—ฒ ๐—ง๐—ฒ๐—ฟ๐—บ๐˜€: ๐˜€๐˜‚๐—บ(๐—ฎ, ๐—ฏ, ๐—ฐ) โ€”> ๐˜€๐˜‚๐—บ๐Ÿฌ(๐—ฎ) => ๐˜€๐˜‚๐—บ๐Ÿญ(๐—ฏ) => ๐˜€๐˜‚๐—บ๐Ÿฎ(๐—ฐ)

๐—˜๐˜…๐—ฎ๐—บ๐—ฝ๐—น๐—ฒ ๐Ÿ‘‡

const sum = (a) => {
 return (b) => {
  return (c) => {
   return a + b + c;
  };
 };
};

const sum = (a) => (b) => (c) => a + b + c;

๐—›๐—ผ๐˜„ ๐˜๐—ผ ๐—ฐ๐—ฎ๐—น๐—น ๐˜๐—ต๐—ฒ ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป?

๐Ÿฌ) sum(10)(20)(30); // 60
๐Ÿญ) const addTen = sum(5)(5);
addTen(20); // 30

ย