上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} fn
*/
function memoize(fn) {
return function(...args) {
}
}
/**
* let callCount = 0;
* const memoizedFn = memoize(function (a, b) {
* callCount += 1;
* return a + b;
* })
* memoizedFn(2, 3) // 5
* memoizedFn(2, 3) // 5
* console.log(callCount) // 1
*/
typescript 解法, 执行用时: 448 ms, 内存消耗: 80.8 MB, 提交时间: 2023-04-17 16:09:35
type Fn = (...params: any) => any
function memoize(fn: Fn): Fn {
const cache = new Map<string, unknown>()
return function (...args) {
const key = args.join('#')
if (cache.has(key)) return cache.get(key)
const res = fn.apply(this, args)
cache.set(key, res)
return res
}
}
/**
* let callCount = 0;
* const memoizedFn = memoize(function (a, b) {
* callCount += 1;
* return a + b;
* })
* memoizedFn(2, 3) // 5
* memoizedFn(2, 3) // 5
* console.log(callCount) // 1
*/
javascript 解法, 执行用时: 296 ms, 内存消耗: 79.6 MB, 提交时间: 2023-04-17 16:09:19
/**
* @param {Function} fn
*/
function memoize(fn) {
let m = new Map();
return function(...args) {
let p = args.join(',');
if ( !m.has(p) ) {
m.set(p, fn(...args));
}
return m.get(p);
}
}
/**
* let callCount = 0;
* const memoizedFn = memoize(function (a, b) {
* callCount += 1;
* return a + b;
* })
* memoizedFn(2, 3) // 5
* memoizedFn(2, 3) // 5
* console.log(callCount) // 1
*/