I am trying to clear the memoized cache object but tried different solutions like prototype, call and bind but not able to make it work. Any help would be appreciated.
function memoize(func) {
let cache = {};
return function() {
function clear() { cache = {}; }
const key = JSON.stringify(arguments);
if(cache[key]) { return cache[key]; }
const result = func.apply(this, arguments);
cache[key] = result;
return result;
}
}
function square(num) {
console.log('calling square of', num);
return num*num;
}
const memoizedSquare = memoize(square);
memoizedSquare(1);
memoizedSquare(1);
memoizedSquare(2);
memoizedSquare.clear(); // getting error on this line
memoizedSquare(2);
memoizedSquare(3);
function addition(a,b,c,d) {
console.log('calling addition of', a,b,c,d);
return a+b+c+d;
}
const memoizedAddition = memoize(addition);
memoizedAddition(1,2,3,4);
memoizedAddition(1,2,3,4);
memoizedAddition(4,2,3,1);
memoizedAddition(6,7,8,9);
memoizedAddition(6,7,8,9);