Skip to content

Instantly share code, notes, and snippets.

@Bor1s
Created February 25, 2026 14:29
Show Gist options
  • Select an option

  • Save Bor1s/4d67880d2c097c9a1f04e1d9f49319a4 to your computer and use it in GitHub Desktop.

Select an option

Save Bor1s/4d67880d2c097c9a1f04e1d9f49319a4 to your computer and use it in GitHub Desktop.
LRU Cache — TypeScript pair programming exercise

LRU Cache — TypeScript

An in-memory cache implementation that expires the least recently used items, and limits cache size by a maximum number of items.

API

A cache object can be instantiated in memory. It requires the max number of records as an argument:

const cache = new Cache<string>({ maxSize: 100 });

An object may be written to a string cache key (returns the written value):

cache.write("key", value);

That object may be retrieved by a key, or null is returned if it is not found:

cache.read("key");

A cached value may be deleted by key:

cache.delete("key");

All values may be deleted (returns number of deleted items):

cache.clear();

The number of records can be fetched at any time:

cache.count;

The cache contents can be inspected as a plain object:

cache.toObject();

Example

const cache = new Cache<string>({ maxSize: 3 });

cache.toObject();
// => {}

cache.write("key1", "val1");
// => "val1"

cache.toObject();
// => { key1: "val1" }

cache.write("key2", "val2");
// => "val2"

cache.toObject();
// => { key1: "val1", key2: "val2" }

cache.write("key3", "val3");
// => "val3"

cache.toObject();
// => { key1: "val1", key2: "val2", key3: "val3" }

cache.write("key4", "val4");
// => "val4"

cache.toObject();
// => { key2: "val2", key3: "val3", key4: "val4" }

cache.read("key1");
// => null

cache.read("key2");
// => "val2"

cache.toObject();
// => { key2: "val2", key3: "val3", key4: "val4" }

cache.write("key5", "val5");
// => "val5"

cache.write("key6", "val6");
// => "val6"

cache.toObject();
// => { key2: "val2", key5: "val5", key6: "val6" }

cache.count;
// => 3

cache.write("key5", "value5-overwrite");
// => "value5-overwrite"

cache.read("key5");
// => "value5-overwrite"

cache.clear();
// => 3

cache.toObject();
// => {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment