高阶函数(Higher-order Functions)

接受函数作为参数或返回函数的函数。


📚 基本概念

定义

高阶函数是:

  1. 接受函数作为参数的函数
  2. 返回函数的函数
  3. 或两者兼有
// 接受函数作为参数
function map(array, fn) {
  return array.map(fn);
}
 
// 返回函数
function multiplyBy(n) {
  return function(x) {
    return x * n;
  };
}

🎯 常见高阶函数

1. Array.map()

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]

2. Array.filter()

const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

3. Array.reduce()

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 10

4. Array.forEach()

const numbers = [1, 2, 3];
numbers.forEach(n => console.log(n));
// 1
// 2
// 3

5. Array.find()

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: 'Bob' }

6. Array.some() 和 Array.every()

const numbers = [1, 2, 3, 4];
console.log(numbers.some(n => n > 3)); // true
console.log(numbers.every(n => n > 0)); // true

🔧 自定义高阶函数

1. 函数组合器

function compose(...fns) {
  return function(value) {
    return fns.reduceRight((acc, fn) => fn(acc), value);
  };
}
 
const add1 = x => x + 1;
const multiply2 = x => x * 2;
const add1ThenMultiply2 = compose(multiply2, add1);
console.log(add1ThenMultiply2(3)); // 8 (3+1)*2

2. 函数柯里化

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    } else {
      return function(...nextArgs) {
        return curried.apply(this, args.concat(nextArgs));
      };
    }
  };
}
 
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6

3. 防抖(Debounce)

function debounce(fn, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}
 
const debouncedSearch = debounce((query) => {
  console.log(`Searching for: ${query}`);
}, 300);

4. 节流(Throttle)

function throttle(fn, delay) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      return fn.apply(this, args);
    }
  };
}
 
const throttledScroll = throttle(() => {
  console.log('Scrolling...');
}, 100);

💡 实际应用

1. 数据处理管道

const users = [
  { name: 'Alice', age: 25, active: true },
  { name: 'Bob', age: 30, active: false },
  { name: 'Charlie', age: 35, active: true }
];
 
const activeUsersOver25 = users
  .filter(user => user.active)
  .filter(user => user.age > 25)
  .map(user => user.name);
 
console.log(activeUsersOver25); // ['Charlie']

2. 函数式工具库

// 使用 Lodash 的函数式方法
import _ from 'lodash';
 
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
];
 
const names = _.map(users, 'name');
const totalAge = _.sumBy(users, 'age');

3. React 中的高阶组件

function withLoading(Component) {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <Component {...props} />;
  };
}

🔗 相关链接


参考


javascript 函数式编程 高阶函数 functional-programming