LFUCache/LRUCache : convert live code example to Jest test.

This commit is contained in:
Eric Lavault
2021-10-09 18:01:42 +02:00
parent 5c4be7604d
commit ab7e51909a
4 changed files with 110 additions and 76 deletions

View File

@ -86,41 +86,4 @@ class LRUCache {
}
}
function main () {
// Example 1 (Small Cache)
const cache = new LRUCache(2)
cache.set(1, 1)
cache.set(2, 2)
console.log(cache.get(1))
cache.set(3, 3)
console.log(cache.get(2)) // cache miss
cache.set(4, 4)
console.log(cache.get(1)) // cache miss
console.log(cache.get(3))
console.log(cache.get(4))
console.log('Example Cache: ', cache.cacheInfo(), '\n')
// Example 2 (Computing Fibonacci Series - 100 terms)
function fib (num, cache = null) {
if (cache) {
const value = cache.get(num)
if (value) { return value }
}
if (num === 1 || num === 2) { return 1 }
const result = fib(num - 1, cache) + fib(num - 2, cache)
if (cache) { cache.set(num, result) }
return result
}
const fibCache = new LRUCache(100)
for (let i = 1; i <= 100; i++) { fib(i, fibCache) }
console.log('Fibonacci Series Cache: ', fibCache.cacheInfo(), '\n')
}
main()
export { LRUCache }