Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda