Sobes.tech
Senior

const createCachedSum = function (a, b) { } const sum = createCachedSum() console.log(sum(2, 3)) // 5 console.log(sum(2, 3)) // cached console.log(sum(4, 1)) // cached

sobes.tech AI

Answer from AI

javascript const createCachedSum = function() { const cache = new Map(); return function(a, b) { const key = ${a},${b}; if (cache.has(key)) { console.log('from cache'); return cache.get(key); } const result = a + b; cache.set(key, result); return result; }; };

const sum = createCachedSum();

console.log(sum(2, 3)); // 5 console.log(sum(2, 3)); // 5 from cache console.log(sum(4, 1)); // 5

Here, the function createCachedSum creates a closure with an internal cache. When calling the sum function with arguments, it checks if the result is in the cache; if yes, it returns the stored value, otherwise it calculates the sum and stores it.