AkashBabu / lfu-cache

LFU cache implementation with a complexity of `O(1)` for all transactions
MIT License
7 stars 0 forks source link

Cache size issue #1

Closed SukkaW closed 4 years ago

SukkaW commented 4 years ago
const LFU = require('@akashbabu/lfu-cache');
const cache = new LFU();

// Generate random number
const random = (min, max) => Math.round(Math.random() * (max - min)) + min;

const cacheFunc = (key, value) => {
  if (typeof cache.peek(key) !== 'undefined') return cache.get(key);
  cache.set(key, value);
  return value;
}

//  "cold" will be called only once
cacheFunc('cold', '123');
// "hot" will be called for 20 times
for (let i = 1; i <= 20; i++) {
  cacheFunc('hot', '456');
}

// Let the cache size limit exceeded
for (let i = 1; i <= 200; i++) {
  // all of them will be called three times
  cacheFunc(String(100 + i),  random(100, 900));
  cacheFunc(String(100 + i),  random(100, 900));
  cacheFunc(String(100 + i),  random(100, 900));
}

// "new" will be called once
cacheFunc('new', '123');

console.log('cold: ' + cacheFunc('cold', '789'));
// Should be 789 not 123, because the cold cache will be removed from the cache.
console.log('hot: ' + cacheFunc('hot', '789'));
// Should be 456 not 789, because it is hot and remains in the cache.
console.log('new: ' + cacheFunc('new', '789'));
// Should be 123 not 789, because it is a new item added to the cache.
console.log(cache.size);
// Should be 100, because max size is 100 by default

Results in:

"cold: 123"
"hot: 456"
"new: 123"
203

https://runkit.com/sukkaw/5e3010ce1bb7e20014bc02e9

AkashBabu commented 4 years ago

@SukkaW Thank you for reporting this bug 👏 Bug has been fixed in @akashbabu/lfu-cache@1.0.2. Please update your library and try again.