LRU Cache in Javascript

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.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why to have a Service-Controller architecture for every backend app?

Understanding Difference between ES5 and ES6 (with example code)

“zsh compinit: insecure files” Prompt on oh-my-zsh

環境 | Electron + Python + Vue

Apollo Multiple Clients with React?

Using React Hooks to Make API Calls

Class based counter example

Figma tokens automatically turned into code: how we kickstarted our design system

OOP in JavaScript

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
Dustin Morris

Dustin Morris

More from Medium

JavaScript Promise: The Ultimate Promise

Promises In JAVASCRIPT

Expressing Functions in JavaScript

Abstraction in Javascript