An LRU cache (problem 20.3) evicts whatever was used longest ago. That is a poor choice when a few entries are used all the time and a stream of others are used once: one pass through a long list pushes the site logo, the current user and the translation table out of the cache. An LFU cache (least frequently used) counts how often each entry is used and evicts the one with the smallest count, so popular entries survive a scan.
Write an LFUCache class in lfu-cache.js. Like a good LRU, it must do every get and set in constant time.
classLFUCache {constructor(capacity, onEvict) // capacity: a positive integer; onEvict(key, value) optionalgetsize()get(key) // the value, or undefined; counts one usepeek(key) // the value, or undefined; counts nothinghas(key) // true or false; counts nothingfrequency(key) // how many uses key has, or 0set(key, value) // new key: 1 use; existing key: one more use; returns the cachedelete(key) // true if it was therekeys() // the keys in the order they would be evictedclear()}
capacity must be a positive integer (RangeError); onEvict, when given, must be a function (TypeError).
A new key starts with 1 use. Each get or set of an existing key adds 1. has, peek and misses count nothing. frequency of a missing key is 0.
When a new key arrives in a full cache, the entry with the fewest uses is evicted; among entries with the same count, the least recently used one. Room is made before the new key is added, so it is never its own victim.
Setting an existing key updates its value and evicts nothing.
keys() lists the keys in eviction order: fewest uses first, and within a count, least recently used first.
onEvict(key, value) is called for each evicted entry, after it has been removed. delete, overwriting and clear are not evictions.
delete returns whether the key was there and frees a place. A deleted key that comes back starts again at 1.
An entry holding undefined is an entry, and get on it counts. Keys are compared like Map keys.
Counts never decrease: an entry used many times long ago stays ahead of newer entries with fewer uses.
get and set take constant time: 200,000 operations with many evictions on a cache of 20,000 entries finish well within the time limit.
Plain JavaScript in a browser page; the tests create new LFUCache(…) from lfu-cache.js.
Any built-in is allowed. One test runs 200,000 random operations, half of them misses, so searching all entries for the smallest count on each eviction fails on time.
Out of scope: ageing counts over time, weights per entry, and expiry.