Cache em JavaScript
// to create a cache, you can use an IIFE to return a function with access to a local variable:
const functionWithCache = (function() {
const cache = {};
return function(num) {
// example: returns whether an input number is even or not
return num % 2 === 0;
};
})();
// you can use this to memoize functions:
const memoizedFunction1 = (function() {
const cache = {};
return function(num) {
if (num in cache) {
return cache[num];
}
// example: returns whether an input number is even or not
return cache[num] = num % 2 === 0;
};
})();
// for more complex parameters:
const memoizedFunction2 = (function() {
const cache = {};
return function() {
const cacheQuery = Array.from(arguments).map((arg) => JSON.stringify(arg)).join(",");
if (cacheQuery in cache) {
return cache[cacheQuery];
}
// function body
return cache[cacheQuery] = result;
};
})();
// with that we can create a function to convert other functions into memoized functions:
function memoize(func) {
const cache = {};
return function() {
const args = Array.from(arguments);
const cacheQuery = args.map((arg) => JSON.stringify(arg)).join(",");
if (cacheQuery in cache) {
return cache[cacheQuery];
}
return cache[cacheQuery] = func(...args);
};
}
MattDESTROYER