UNPKG

ut2

Version:

一个现代 JavaScript 实用工具库。[点击查看在线文档]。

37 lines (34 loc) 1.11 kB
import shallowEqual from './shallowEqual.js'; import { mathCeil } from './internals/native.js'; function memoize(func, options) { var opts = options || {}; var max = mathCeil(opts.max || 0); var isEqual = typeof opts.isEqual === 'function' ? opts.isEqual : shallowEqual; var cache = []; function memoized() { var _this = this; var newArgs = []; for (var _i = 0; _i < arguments.length; _i++) { newArgs[_i] = arguments[_i]; } var cacheValue = cache.find(function (item) { return item.lastThis === _this && isEqual(item.lastArgs, newArgs); }); if (cacheValue) { return cacheValue.lastReturn; } var lastReturn = func.apply(this, newArgs); if (max > 0 && cache.length >= max) { cache.shift(); } cache.push({ lastArgs: newArgs, lastThis: this, lastReturn: lastReturn }); return lastReturn; } memoized.clear = function () { cache.length = 0; }; return memoized; } export { memoize as default };