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:
https://runkit.com/sukkaw/5e3010ce1bb7e20014bc02e9