Exercise 16: Function Cache (with key generator)
Problem Statement
Create a function `cache(fn, keyGen)` that caches function results with custom key generator.
Sample Output:
const expensive = cache((n) => n * 2, (n) => `num_${n}`);
expensive(5) => 10 (computed)
expensive(5) => 10 (cached)Solution
const cache = (fn, keyGen = JSON.stringify) => {
const memo = new Map();
return (...args) => {
const key = keyGen(...args);
if (memo.has(key)) return memo.get(key);
const result = fn(...args);
memo.set(key, result);
return result;
};
};Explanation
Overall Goal:
- Function results ko cache karna with custom key generation.
Real world:
- Performance: expensive calculations cache.
- API calls: response caching.