Câu hỏi phỏng vấn Javascript
Câu hỏi

Can you give an example of a curry functio...

Câu trả lời

Certainly! Let's discuss an example of a curry function in JavaScript and explore why this syntax offers advantages.

Example of a Curry Function

Consider a simple function that adds three numbers. Normally, you might define it like this:

javascript Copy
function add(x, y, z) {
  return x + y + z;
}

To call this function, you would pass all three arguments at once, like so: add(1, 2, 3).

Now, let's transform this into a curried function:

javascript Copy
function addCurry(x) {
  return function(y) {
    return function(z) {
      return x + y + z;
    };
  };
}

With the curried version, you can call the function like this: addCurry(1)(2)(3).

Advantages of Currying

  1. Partial Application: Currying allows you to create partial functions. This means you can fix some arguments and generate a new function that waits for the rest of the arguments. For example, if you know you frequently need to add 2 and 3 to different numbers, you can create a new function like so: const add5 = addCurry(2)(3); and then use add5(4) to get 9[1][2].

  2. Code Reusability: By breaking down a function that takes multiple arguments into several functions that take one argument each, currying helps in creating more modular and reusable code. Each function generated can be reused with different subsequent arguments[1][2][6].

  3. Higher Order Functions: Currying transforms a multi-argument function into a sequence of higher-order functions, each taking one argument. This is particularly useful in functional programming where functions are treated as first-class citizens[1][2].

  4. Cleaner and More Readable Code: Curried functions can lead to more readable code by minimizing the syntactic noise in the function invocation (less clutter with commas and parentheses). It also helps in creating a clear separation of concerns where each function does one specific thing[1][2].

  5. Function Composition: Curried functions are v...

expert

expert

Gợi ý câu hỏi phỏng vấn

senior

Explain difference between: function Person(){} , var person = Person() , and var person = new Person() ?

middle

What's the difference between using let and var to declare a variable in ES6?

middle

What is the definition of a Higher-Order Function?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào