Skip to content

Lodash - 函数

Lodash 提供了强大的工具,用于处理函数,包括诸如柯里化 (currying)、部分应用 (partial application)、记忆化 (memoization) 和控制函数执行等技术。虽然现代 JavaScript 提供了诸如箭头函数、剩余/展开语法以及 Function.prototype.bind 等特性,但 Lodash 方法在某些模式下仍然可以提供增强的功能或更简洁的语法。

本节涵盖了 Lodash 中用于函数操作和增强的关键方法。

方法与语法描述与现代 JS 对比
bind
_.bind(func, thisArg, [partials])
创建一个函数,该函数以 thisArg 为 this 绑定并将其接收到的参数前置 partials 来调用 func。类似于 Function.prototype.bind,但 Lodash 的 _.bind 允许使用占位符参数。
partial
_.partial(func, [partials])
创建一个函数,该函数将 partials 前置到其接收到的参数来调用 func。对于创建函数的专用版本非常有用。可以通过 Function.prototype.bind(null, ...partials) 或箭头函数闭包实现。
partialRight
_.partialRight(func, [partials])
与 _.partial 类似,但将 partials 从右侧前置到参数中。
curry
_.curry(func, [arity=func.length])
创建一个函数,该函数一次接受 func 的一个参数。如果 func 需要更多参数,它会返回一个等待其余参数的新柯里化函数。在函数式编程中很有用。
curryRight
_.curryRight(func, [arity=func.length])
与 _.curry 类似,但参数是从右到左应用的。
memoize
_.memoize(func, [resolver])
创建一个缓存 func 调用结果的函数。后续使用相同参数的调用将返回缓存结果。对于优化昂贵的计算非常有用。可选的 resolver 决定缓存键。
once
_.once(func)
创建一个函数,该函数只能调用 func 一次。重复调用该函数将返回第一次调用的结果。
before
_.before(n, func)
创建一个函数,只要其被调用的次数少于 n 次就会调用 func。后续调用将返回最后一次 func 调用的结果。
delay
_.delay(func, wait, [args])
在 wait 毫秒后调用 func。提供的任何额外参数将在调用 func 时传递给它。类似于 setTimeout,但在 Lodash 链中常因其更简洁的语法而被使用。
flip
_.flip(func)
创建一个函数,该函数以其前两个参数颠倒的顺序调用 func。
negate
_.negate(predicate)
创建一个否定谓词函数结果的函数。
overArgs
_.overArgs(func, [transforms])
创建一个函数,该函数以其参数被相应的 transforms 函数转换后调用 func。
rearg
_.rearg(func, indexes)
创建一个函数,该函数以根据指定 indexes 重新排列的参数调用 func。
rest
_.rest(func, [start=func.length-1])
创建一个函数,该函数以创建函数的 this 绑定并将其从 start 开始的参数收集到数组中来调用 func。很大程度上已被原生剩余参数语法 (...args) 取代。
spread
_.spread(func, [start=0])
创建一个函数,该函数以创建函数的 this 绑定和参数数组调用 func,非常类似于 Function.prototype.apply。很大程度上已被原生展开语法 (...args) 取代。
unary
_.unary(func)
创建一个最多接受一个参数,忽略任何额外参数的函数。
wrap
_.wrap(value, [wrapper=identity])
创建一个函数,该函数将 value 作为第一个参数提供给 wrapper 函数。传递给创建函数的任何额外参数也会提供给 wrapper。
import _ from 'lodash-es';
let calculations = 0;
// 模拟一个昂贵的函数
function expensiveCalculation(n) {
calculations++;
console.log(`Calculating for ${n}...`);
// 这里是复杂的逻辑...
return n * n;
}
// 创建一个 memoization (记忆化) 版本
const memoizedCalc = _.memoize(expensiveCalculation);
console.log(memoizedCalc(5)); // 输出: Calculating for 5... 25
console.log(memoizedCalc(5)); // 输出: 25 (结果从缓存中获取)
console.log(memoizedCalc(10)); // 输出: Calculating for 10... 100
console.log(memoizedCalc(5)); // 输出: 25 (再次命中缓存)
console.log(memoizedCalc(10)); // 输出: 100 (再次命中缓存)
console.log(`Total calculations performed: ${calculations}`); // 输出: Total calculations performed: 2

Lodash 函数方法在函数式编程范式、性能优化(如 memoization)以及创建高度可重用和可配置的函数逻辑方面特别有价值。

请查阅 Lodash 文档,获取更多高级用法,例如为 _.memoize 使用自定义解析器 (resolver) 或在 _.bind 和 _.partial 中使用占位符 (placeholder)。