-
-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现内存函数缓存函数调用结果 #262
Comments
const cachedFn = (function (fn) {
let cache = {};
return function (...args) {
argsKey = args.toString()
if (argsKey in cache) {
return cache[argsKey];
}
return (cache[argsKey] = fn.apply(this, args));
};
})(fn); |
const map = new Map(); return function(...args) { |
利用闭包进行缓存
function catach(fn) {
let cache = new Map();
return function (...args) {
let key = JSON.stringify(args);
if (cache.has(key)) {
console.log("cache");
return cache.get(key);
} else {
let data = fn.apply(this, args);
cache.set(key, data);
return data;
}
};
}
function expensiveFunction(x) {
console.log("Computing...");
return x * x;
}
let cacheAft = catach(expensiveFunction);
console.log(cacheAft(5));
console.log(cacheAft(5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: