LRU Cache in Javascript

Least Recently Used Cache Algorithm

I practice algorithms everyday. My go to websites for algorithm practice are and

This particular problem is on titled LRU Cache. Least Recently Used Cache is helpful for removing old cache items thereby maintaining a fixed memory space and limiting the cache size for faster cache searches.

You can imagine where this would be useful such as page searches, frequent word use, or load-balancing servers.

The inputs are:

Cache Capacity as an integer.

Key/Value pairs.

The methods are:


put(key, value)

To solve this problem, I decided to use Javascript’s Map class. Maps are similar to objects except they remember their insertion order. This is exactly the data structure needed. It needs to remember the order it was inserted and it has key/value pairs. The trick with using Maps in this case was if the key already existed in the Map, then I deleted it and reinserted it. This put the key/value pair at the end of the Map.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store