자바스크립트 커링 (Currying)

In functional programming, currying is a technique where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument. This allows for partial application of the function, which can be useful in many scenarios.

How does currying work?

Currying involves transforming a function with n arguments into a chain of n functions, each taking one argument. Consider the following example:

function add(a, b, c) {
  return a + b + c;
}

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

console.log(add(1, 2, 3)); // Output: 6
console.log(curriedAdd(1)(2)(3)); // Output: 6

The original add function takes three arguments and returns their sum. Using currying, we can create a curriedAdd function that takes one argument at a time and returns a new function that takes the next argument until all arguments are provided. This allows us to call curriedAdd with one argument at a time or all arguments at once.

Benefits of currying

Partial function application

Currying provides a way to create new functions by partially applying the original function with some of its arguments. This can be useful when you have a function that is commonly used with some fixed arguments.

const multiply = (a, b) => a * b;
const double = multiply(2); // Partially applied function

console.log(double(3)); // Output: 6
console.log(double(5)); // Output: 10

In this example, we create a new function double by partially applying the multiply function with the argument 2. The resulting double function can now be used to easily calculate the double of any number.

Function composition

Currying allows for easy function composition, which is the process of combining two or more functions to produce a new function. By currying the functions, we can easily chain them together.

const add = (a) => (b) => a + b;
const multiply = (a) => (b) => a * b;
const doubleAndAdd = (x) => add(multiply(2)(x))(x);

console.log(doubleAndAdd(3)); // Output: 9 (2 * 3 + 3)
console.log(doubleAndAdd(5)); // Output: 15 (2 * 5 + 5)

In this example, the doubleAndAdd function is created by combining the add function and the multiply function using function composition. The doubleAndAdd function first doubles the input value and then adds it to the original value. This allows for reusable and composable code.

Conclusion

Currying is a powerful technique in functional programming that allows for partial function application and function composition. It provides a more flexible and modular way of working with functions, allowing for code reuse and cleaner code structure. By understanding how currying works and its benefits, you can take advantage of this technique in your JavaScript projects.