A simple LRU Cache in TypeScript
ES6 Map ftw!
Today, I’d like to present a simple in-memory cache implementation written in TypeScript. It uses the least-recently used (LRU) cache eviction strategy. Very simplified, LRU is a strategy where you “try to remember what people read” and “it’s ok to forget what people do not read”.
When inserting new items into the cache, we need to check whether the maximum size is exceeded. If yes, we evict (i.e. remove) the least-recently used item from the cache.
When reading items from the cache, we need to remember that item as the most-recently used item. In TypeScript code it looks like that:
The key here is the usage of the EcmaScript 2015 (ES6) Map object. A Map keeps track of the insertion order:
A
Mapobject iterates its elements in insertion order — afor...ofloop returns an array of[key, value]for each iteration.
When iterating over the Map, the first item is the one which was inserted first. In result, values.keys().next() returns the least-recently used key. In order to “remember” the most-recently used items, we need to re-insert them — .delete() followed by .set() — when reading items from the cache.
The above code is obviously a very simple implementation. In advanced solutions, you can persist the data to localStorage, so that it “survives” page refreshes but you need to maintain the insertion order in locale storage on your own!
If this article was helpful to drop me some feedback! 💬

