ut2
Version:
一个现代 JavaScript 实用工具库。[点击查看在线文档]。
39 lines (35 loc) • 1.13 kB
JavaScript
;
var shallowEqual = require('./shallowEqual.js');
var native = require('./internals/native.js');
function memoize(func, options) {
var opts = options || {};
var max = native.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;
}
module.exports = memoize;