Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Remove oldest entry in Map() with O(1) time complexity JS

If we want to keep fixed size of a map - 3 entries and remove oldest touched entry, when new one is created, how do we do it with constant time? (I got told it's possible)

If we do such operations:

let cache = new Map()

cache.set('one', 1);
cache.set('two', 2);
cache.set('three', 3);

cache.set('two', 'two');

cache.set('four', 4);

I'd expect map then to be:

{
    ['three', 3],
    ['two', 'two'],
    ['four', 4],
}

I can think only of having O(n) solution for invalidation, but it defeats whole purpose of cache.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Maps are iterated in the order in which the keys were created. So you can use that to do

const cache = new Map();
const keysIter = cache.keys();
function set(key, value) {
    cache.set(key, value);
    if (cache.size > 3) {
        cache.delete(keysIter.next().value);
    }
}

If however by "oldest touched" you want to refer to updates, not just to creation (e.g. in your example, cache.set('five', 5) would evict ['three', 3] not ['two', 'two']), you will need to keep track of these touches yourself, e.g. in a circular buffer. Or maybe just call cache.delete(key) every time before "updating", so that the cache.set(key, value) always creates a new entry at the end.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!