双语面试:实现一个组合函数

0 阅读1分钟

面试题 Interview Question

实现一个函数 compose,用于从右到左组合多个函数。
Implement a compose function that composes multiple functions from right to left.

要求 Requirements

  1. compose(...fns) 接收多个函数作为参数
    compose(...fns) takes multiple functions as input
  2. 返回一个新函数,该函数会按从右到左的顺序依次执行传入的函数
    Returns a new function that executes the passed-in functions from right to left
  3. 支持任意数量的函数,且每个函数只能接收一个参数(即单参函数)
    Should support any number of unary functions (functions that take a single argument)
  4. 不使用 this,保持纯函数式风格
    Must use pure functional programming style (no this)

参考答案 Reference Solution

function compose(...fns) {
  return function (initialValue) {
    return fns.reduceRight((acc, fn) => fn(acc), initialValue);
  };
}

示例 Example

const double = x => x * 2;
const square = x => x * x;

const composed = compose(square, double); // 相当于 square(double(x))

console.log(composed(3)); // 输出 Output: 36
// 解释:double(3) = 6,square(6) = 36

面试考察点 Interview Focus

  • 对函数式编程核心概念(组合、管道、柯里化等)的理解
    Understanding of functional programming concepts like composition, piping, currying
  • 对高阶函数、闭包、reduce 等的实际掌握
    Proficiency with higher-order functions, closures, and reduce