双语面试:实现一个柯里化函数

64 阅读1分钟

面试题 Interview Question

实现一个函数 curry,可以把任意多参数函数转换成支持多次调用的柯里化函数。
Implement a function curry that transforms any multi-argument function into a curried version that supports multiple chained calls.

要求 Requirements

  1. curry(fn) 接收一个多参数函数 fn,返回一个可以逐个接收参数的函数
    curry(fn) takes a function fn with multiple parameters and returns a new function that can take arguments one by one
  2. 支持如下调用方式:
    The resulting function should support the following usage:
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);

curriedAdd(1)(2)(3); // 输出 6 → Outputs: 6
curriedAdd(1, 2)(3); // 输出 6 → Outputs: 6
curriedAdd(1)(2, 3); // 输出 6 → Outputs: 6
  1. 不使用全局变量,不使用 this,保持纯函数风格
    Do not use global variables or this, keep the implementation in a pure functional style

参考答案 Reference Solution

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn(...args);
    } else {
      return (...nextArgs) => curried(...args, ...nextArgs);
    }
  };
}

示例 Example

function multiply(a, b, c) {
  return a * b * c;
}

const curriedMultiply = curry(multiply);

console.log(curriedMultiply(2)(3)(4));    // 输出 Output: 24
console.log(curriedMultiply(2, 3)(4));    // 输出 Output: 24
console.log(curriedMultiply(2)(3, 4));    // 输出 Output: 24

面试考察点 Interview Focus

  • 对函数柯里化与偏函数的理解
    Understanding of currying vs. partial application

  • 函数参数处理技巧(rest/spread 运算符)
    Handling function arguments with rest/spread syntax

  • 闭包和函数式编程思想掌握程度
    Mastery of closures and functional programming concepts