FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
Memoization is a widely used technique in programming to optimize performance by caching the results of expensive function calls. Implement a general memo function in JavaScript that caches the results of function calls based on the arguments passed in. The memo function should return the cached result if the same arguments are provided again, without re-evaluating the function.
Use the following function as an example:
const factorial = (n) => {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
};
const memoedFactorial = memo(factorial);
console.log(memoedFactorial(5));
// Output: 120 (factorial is called)
console.log(memoedFactorial(5));
// Output: 120 (returned right away without calling factorial)
console.log(memoedFactorial(6));
// Output: 720 (new argument, so factorial is called)
Your task is to complete the implementation of the memo function and ensure it behaves as described above.
Template
index.js
export function memo(func) {
}
index.test.js
import { memo } from './';
describe('memo function', () => {
it('should memoize function calls', () => {
const expensiveFunction = jest.fn((x, y) => x + y);
const memoizedFunction = memo(expensiveFunction);
memoizedFunction(2, 3);
memoizedFunction(2, 3);
memoizedFunction(2, 3);
// Ensure the expensive function is called only once
expect(expensiveFunction).toHaveBeenCalledTimes(1);
});
it('should memoize function calls with different arguments', () => {
const expensiveFunction = jest.fn((x, y) => x + y);
const memoizedFunction = memo(expensiveFunction);
memoizedFunction(2, 3);
memoizedFunction(3, 4);
memoizedFunction(2, 3);
memoizedFunction(3, 4);
expect(expensiveFunction).toHaveBeenCalledTimes(2);
});
});
Info
Question
Memoization is a widely used technique in programming to optimize performance by caching the results of expensive function calls. Implement a general memo function in JavaScript that caches the results of function calls based on the arguments passed in. The memo function should return the cached result if the same arguments are provided again, without re-evaluating the function.
Use the following function as an example:
Your task is to complete the implementation of the memo function and ensure it behaves as described above.
Template
index.js
index.test.js