Objective: Implement a memoization function that caches the results of function calls to improve performance.
Instructions:
memoize
that takes a function as an argument and returns a new function that caches the results of the function.Example Usage:
const slowFunction = (num) => {
// Simulate a slow computation
return new Promise((resolve) => {
setTimeout(() => resolve(num * 2), 3000); // Simulates a 3-second delay
});
};
const memoizedFunction = memoize(slowFunction);
memoizedFunction(5).then(result => console.log(result)); // Calls slowFunction, outputs: 10 after 3 seconds
memoizedFunction(5).then(result => console.log(result)); // Returns cached result, outputs: 10 immediately
Requirements:
memoize
function should cache the result of previous function calls based on the arguments provided.Hints:
object
or Map
to store the function arguments and their corresponding results.Bonus: