LRU Cache in Javascript

Least Recently Used Cache Algorithm

Dustin Morris
1 min readOct 11, 2020

I practice algorithms everyday. My go to websites for algorithm practice are leetcode.com and algoexpert.io

This particular problem is on leetcode.com 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:

get(key)

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.

--

--