자바스크립트 커링 (Currying)

Currying is a functional programming technique that allows us to create reusable and composable functions. It is named after the mathematician Haskell Curry, who introduced the concept.

What is Currying?

Currying is the process of transforming a function that takes multiple arguments into a series of nested functions that each take a single argument. This technique allows us to partially apply arguments to a function, creating new functions with pre-set values.

Example

Let’s take a look at a simple example to understand how currying works in JavaScript.

// Without currying
function add(a, b) {
  return a + b;
}

// With currying
function addCurried(a) {
  return function(b) {
    return a + b;
  };
}

// Usage
const add2 = addCurried(2); // This creates a new function with 'a' set to 2
console.log(add2(3)); // Output: 5

In the above example, we have a function called add that takes two arguments and returns their sum. We also have a curried version of the add function called addCurried.

To use the curried function, we first call addCurried(2) and store the returned function in the variable add2. This creates a new function with the first argument, a, set to 2. Then, we call add2(3), which adds the second argument, b, to the pre-set value of a. The result is 5.

Benefits of Currying

Currying provides several benefits:

Implementing Currying in JavaScript

Although JavaScript does not natively support currying, we can easily implement it using either nested functions or currying libraries such as Lodash or Ramda.

Here’s an example of implementing currying using nested functions:

function addCurried(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    };
  };
}

const add = addCurried(2)(3);
console.log(add(4)); // Output: 9

Conclusion

Currying is a powerful technique in functional programming that allows us to create reusable and composable functions. By transforming a function that takes multiple arguments into a series of nested functions, we gain the ability to partially apply arguments and create new functions with pre-set values. This can lead to increased code reusability, modularity, and flexibility in our JavaScript applications.