上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} fn
*/
function memoize(fn) {
return function() {
}
}
/**
* 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 解法, 执行用时: 320 ms, 内存消耗: 97.9 MB, 提交时间: 2023-04-17 16:12:47
/**
* @param {Function} fn
*/
function memoize(fn) {
var index = 0;
// 参数arg -> 参数arg对应的唯一索引
var argIndexMap = new Map();
var cache = new Map();
return (...args) => {
// 参数列表[...args]对应的索引数组,根据索引数组判断是否命中缓存
var argIndexes = [];
for (var arg of args) {
if (!argIndexMap.has(arg)) {
var argIndex = index++;
argIndexMap.set(arg, argIndex);
argIndexes.push(argIndex);
} else {
argIndexes.push(argIndexMap.get(arg));
}
}
// 将索引数组转换成字符串
var key = argIndexes.join("-");
if (cache.has(key)) {
return cache.get(key);
} else {
var value = fn(...args);
cache.set(key, value);
return value;
}
}
}
/**
* 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 解法, 执行用时: 320 ms, 内存消耗: 102.3 MB, 提交时间: 2023-04-17 16:12:21
type Fn = (...params: any) => any
function memoize(fn: Fn): Fn {
const idPool = new Map<unknown, number>()
const cache: Map<string, ReturnType<Fn>> = new Map()
return function (...args: Parameters<Fn>): ReturnType<Fn> {
const key = args.map(getId).join(',')
if (cache.has(key)) {
return cache.get(key)!
}
const res = fn(...args)
cache.set(key, res)
return res
}
function getId(o: unknown): number {
if (idPool.has(o)) {
return idPool.get(o)!
}
const id = idPool.size
idPool.set(o, id)
return id
}
}
/**
* 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
*/