@gvray/eskit
Version:
A rich and colorful toolkit about typescript and javascript.
84 lines • 2.91 kB
JavaScript
;
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Creates a memoized version of a function that caches results for identical arguments.
* 创建函数的记忆化版本,为相同参数缓存结果。
*
* The memoized function will cache the result of the first call with specific arguments
* and return the cached result on subsequent calls with the same arguments.
* 记忆化函数将缓存第一次调用特定参数的结果,
* 并在后续使用相同参数调用时返回缓存的结果。
*
* @template T - The type of the function to memoize / 要记忆化的函数类型
* @param fn - The function to be memoized / 要记忆化的函数
* @returns The memoized function / 记忆化的函数
*
* @example
* ```typescript
* // Expensive calculation function
* function fibonacci(n: number): number {
* if (n <= 1) return n
* return fibonacci(n - 1) + fibonacci(n - 2)
* }
*
* const memoizedFib = memoize(fibonacci)
*
* console.log(memoizedFib(40)) // First call - calculates result
* console.log(memoizedFib(40)) // Second call - returns cached result instantly
*
* // Works with multiple arguments
* const expensiveOperation = (a: string, b: number) => {
* console.log('Computing...')
* return `${a}-${b * 2}`
* }
*
* const memoized = memoize(expensiveOperation)
* memoized('test', 5) // Logs "Computing..." and returns "test-10"
* memoized('test', 5) // Returns "test-10" without logging
* ```
*
* @since 1.0.0
*/
var memoize = function (fn) {
var cache = new Map();
return (function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
var result = fn.apply(void 0, __spreadArray([], __read(args), false));
cache.set(key, result);
return result;
});
};
exports.default = memoize;
//# sourceMappingURL=memoize.js.map