I have been asked this question and I wasn't sure how I can target this.
Question:
Write a cache function which caches a function and returns a result if it was already executed in the past.
Let's say if there's a function Fibonacci(20) = 6765
cacheFunction(Fibonacci(20)) // it should not execute the function instead return 6765.
But if i give cacheFunction(Fibonacci(21)) //It's not cached, execute the function
My attempt:
function cacheFunction(funct) {
var obj = {};
if (obj.hasOwnProperty(funct)) { //checking if the argument is in the object?
return obj[funct];
} else { //if not present, then execute the function, store it in cache and return the value.
obj[funct];
return funct;
}
}
But I'm not able to understand how to get the arguments in one function inside another function? (The person told me that I need to use closure to get it)
Can someone enlighten me?