DEV Community

Cover image for Implementing a Simple LRU Cache in JavaScript

Implementing a Simple LRU Cache in JavaScript

Sean Welsh Brown on September 03, 2020

In your travels as a software engineer, you're likely to come across instances where every possible data structure gets a chance to shine. One in p...
Collapse
 
bias profile image
Tobias Nickel

when get a key and it is not there, I would return undefined or an error. -1 could also be the value. It reminds me to the time when we needed if (array.indexOf(needle)===-1);{...} and today we have array.includes.

It is very interesting how you are using the iterator from cache.keys().

also, it would be interesting to add a time-to-life, but that can be a good homework 😊

Collapse
 
seanwelshbrown profile image
Sean Welsh Brown

Thanks for your feedback Tobias! I was wondering what the best return value would be for when a key wasn't found, you're definitely right about "undefined" or throwing an error being better than returning a string. I'll edit that part to make it a bit more clear.

Also a great suggestion to add a timed-life option, I'll start thinking about how to implement that!

Collapse
 
pentacular profile image
pentacular

Delegate the problem to the caller -- have them provide a value to return in the not-found case.

Collapse
 
anarkrypto profile image
Kaique 3.0

a small improve to the code, instead of:

   if (this.cache.size === this.capacity) {
     this.cache.delete(this.cache.keys().next().value);
     this.cache.set(key, value);
   } else {
     this.cache.set(key, value);
   }
Enter fullscreen mode Exit fullscreen mode

Just do:

   if (this.cache.size === this.capacity) {
     this.cache.delete(this.cache.keys().next().value);
   }
   this.cache.set(key, value);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sofialevin profile image
Sofia Levin

Wow, TIL about Map objects. Great article, thanks for sharing!

Collapse
 
seanwelshbrown profile image
Sean Welsh Brown

You're very welcome! Thanks so much for reading. I only recently started learning about Map and Set objects myself, and about how they differ from standard JavaScript objects. They're super useful for certain situations like this.

Collapse
 
devtony101 profile image
Miguel Manjarres

Is the first time I heard about this data structure, it seems very useful. Thanks for sharing! Awesome post and explanation

Collapse
 
ghanshyamkdobariya profile image
Ghanshyam

Thank you for posting this. This is really helpful. I liked explanations and clean code.

Collapse
 
lalit_kumar_f50f9cb0482b8 profile image
Lalit Kumar

Thanks for posting this, but it would be great if you can also add the time complexity of get and put methods.

Collapse
 
paras231 profile image
paras231

great post thanks

Collapse
 
ebe25 profile image
Vedansh bisht

great post man, very helpful. Since recently heard about this ds, would try to implement in my project.