Sobes.tech
Senior

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

sobes.tech AI

Vastus AI-lt

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 createCachedSum function is created, which returns a closure with an internal cache. When calling the sum function with arguments, it checks if the result is already in the cache; if so, it returns the stored value, otherwise it calculates the sum and stores it.