The Map data structure stores key-value pairs and remember the order in which the keys were inserted. Any value, whether an object or a primitive value, can be used as either a key or a value.
Implementing a memoization cache for a function
Memoization is a programming optimization technique that makes applications more efficient and thus faster. It accomplishes this by caching computation results and retrieving that same information from the cache the next time it is required rather than computing it again.
function expensiveOperation(arg) {
// simulate an expensive computation
return new Promise(resolve => setTimeout(function() {
resolve(arg + 1)
}, 5000))
}
const cache = new Map()
async function memoizedFunction(arg) {
if (cache.has(arg)) {
return cache.get(arg)
}
const res = await expensiveOperation(arg)
cache.set(arg, res)
return res
}
(async function() {
console.time('1st operation')
console.log(await memoizedFunction(58)) // 59
console.timeEnd('1st operation') // 5.007s
console.time('2nd operation')
console.log(await memoizedFunction(58)) // 59 from cache
console.timeEnd('2nd operation') //0.064ms
})()
Top comments (0)