Skip to content

Instantly share code, notes, and snippets.

@nhevia
Created November 29, 2019 20:59
Show Gist options
  • Save nhevia/892fc4cbd0a3a9ad9564f8003256d5a0 to your computer and use it in GitHub Desktop.
Save nhevia/892fc4cbd0a3a9ad9564f8003256d5a0 to your computer and use it in GitHub Desktop.
Test demostrating basic memoization for a cached parameter, using previously calculated result
// our cache
let cache = {
val: null,
res: null
}
const myLongTask = num => {
// if parameter is equal to our cached value, we don't repeat the calculation
if (num === cache.val) {
const t1 = new Date().valueOf()
const t2 = new Date().valueOf()
console.log(`Parameter was memoized. Operation time(ms): ${t2-t1}`)
return cache.res
}
// since parameter was not equal to our cached value, it needs to do the calculations
const t1 = new Date().valueOf()
const res = stress(num) // mock some performance hit
cache = {val: num, res: res} // store parameter and response in our cache
const t2 = new Date().valueOf()
console.log(`Parameter not memoized. Operation time(ms): ${t2-t1}`)
return res
}
// intensive operation
const stress = (num) => {
let newNum = 0
while (newNum < 2000000000) {
newNum += num
}
return newNum
}
// use a combination of different and same parameters
const myArray = [1,2,3,4,4,4,4,4,4,4,4,4,4,5]
// if passing same parameter than one cached = memoized value (instant)
// if passing diff parameter than one cached = recalculation (slow)
myArray.forEach(number => {
myLongTask(number)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment