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);
2
Answers
For your
memoizedSquare.clear()
to work, the function that you return frommemoize()
should have aclear
property added to it. At the moment, your code declares theclear()
function inside of the returned function, but isn’t accessible to your calling code as it isn’t exposed in any way. Since functions are objects in JavaScript, you can add a property to it just like you would with an ordinary object with dot notation, for example:Another, and probably better, design would be to return a pair
memoized, clear
: