PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 15, 2022

[FIXED] How do I delete the first N items from an ES6 Map object without recreating the Map?

 December 15, 2022     ecmascript-6, javascript, syntax     No comments   

Issue

Say I want to delete the first 100 entries of a Map without recreating the map, and also do this in the most efficient way.

Let's say you have a 500 item ES6 Map Object:

let map = new Map(... 500 items)

Currently I do it like this:

const newCache = new Map(
  Array.from(map).slice(100)
)

map.clear()

map = newCache

But this recreates the Map.

The other way is to run over the first 100 keys:

Array.from(map.keys())
     .slice(0, 100)
     .forEach(key => map.delete(key))

But it looks inefficient.


Solution

Based on your comment, you're buildng some kind of a LRU cache. You might consider a better data structure that just a Map. For example,

cache = { deque: Array, index: Map, offset: Int }

When you put element in the cache, you append it to the deque and store its position + offset in the index:

class Cache...

    put(obj) {
        this.deque.push(obj)
        pos = this.deque.length - 1
        this.index.set(key(obj),  pos + this.offset)
    }

When getting element, check it its index of positive

get(obj) {
    pos = this.index.get(key(obj)) - this.offset
    if pos >= 0
       return this.deque[pos]
    // cache miss....

Now, cleaning up the cache won't involve any loops

 clear(count) {
     this.deque.splice(0, count)
     this.offset += count
 }

On a general note, if you want something to be re-created, but need a persistent pointer to it in the same time, you can just wrap the private object into a public one and proxy (some of) private's methods:

class Cache
   this._map = new Map() // feel free to recreate this when needed


    get(x) { return this._map.get(x) }
    set(x, y) { return this._map.set(x, y) }

myCache = new Cache() // this can be saved somewhere else 


Answered By - georg
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing