Vitalik Zaidman Vitalik Zaidman - 8 months ago 63
Javascript Question

ES6 Map object - Best way to delete 100 first items

I'd want to delete the first 100 entries of a Map without recreating the map, and also to be the most efficient way.

So if 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 it 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.

Answer Source

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 its methods:

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


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

myCache = new Cache() // feel free to persist this
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download