A simple LRU Cache in TypeScript

ES6 Map ftw!

David Herges
Jul 30, 2017 · 1 min read

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:

https://gist.github.com/dherges/86012049be7b1263b2e594134ff5816a

The key here is the usage of the EcmaScript 2015 (ES6) Map object. A Map keeps track of the insertion order:

A Map object iterates its elements in insertion order — a for...of loop 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! 💬

Sparkles Blog

Blogging on Angular, TypeScript, and Web Technologies.

David Herges

Written by

Web Application Developer at Agfa HealthCare. Front-end dev w/ Angular and TypeScript. Opinions are my own and not necessarily my employer‘s.

Sparkles Blog

Blogging on Angular, TypeScript, and Web Technologies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade