Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.3 KiB · at b0c0c21

Write createLru, which creates an in-memory least-recently-used cache with string keys and values of any type V.

createLru(capacity):

  • capacity must be a non-negative integer. Anything else fails with { kind: "invalid_capacity" } at creation time.
  • A capacity of 0 is valid: the cache accepts set calls but never stores anything.

The returned cache has these operations:

  • get(key): returns the stored value, or absent if the key is not in the cache. A successful get makes the key the most recently used. A get for a missing key changes nothing.
  • set(key, value): stores the value. If the key already exists, its value is replaced and it becomes the most recently used; the size does not change and nothing is evicted. If the key is new and the cache is full, the least recently used entry is evicted first. The new key becomes the most recently used.
  • delete(key): removes the key. Returns true if the key was in the cache, false otherwise.
  • size(): the number of stored entries.
  • keys(): the stored keys as a new array, most recently used first.

Any value is a legitimate cache value, including 0, "", and false; a stored value must always be distinguishable from a missing key. Keys are arbitrary strings. Separate caches never share state.