I've been debating this topic with my mates at work. I would like to know from you guys, if this is, actually, the right way of implementing the memoization.
function memoize(result) {
let cache = {};
return function() {
if (cache[result]) {
// returns cached result / no calculation
return cache[result];
}
// calculating...
cache[result] = result;
return cache[result];
};
}
function expensiveCalculation() {
let counter = 0;
for (let i = 0; i < 1000000; i++) {
counter += i;
}
return counter;
}
console.time("FirstCalculation");
const memoizedExpensiveCalculation = memoize(expensiveCalculation());
console.timeEnd("FirstCalculation");
console.time("1_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("1_Memoized");
console.time("2_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("2_Memoized");
console.time("3_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("3_Memoized");
The time logs reveals, in fact, the first time takes much more time (which we would expect) and less time afterwards.
something like:
function get(func) {
let cache = {};
return function(key) {
if (key in cache) {
return cache[key];
}
cache[key] = func(key);
return cache[key];
};
}
function expensiveCalculation(param) {
console.log('expensive calculation runs')
let counter = 0;
for (let i = 0; i < 10000; i++) {
counter += i;
}
return param*2;
}
const memo = get(expensiveCalculation)
console.log('start')
console.log('first try');
console.log(memo(10));
console.log('second try');
console.log(memo(10));