-1

I have an object used as index.

const index= {};

I use a counter to get a new key:

var key=0; 
function getNewKey(){
   return ++key;
}

Then I can add object to index:

function addObject(object){
    const key= getNewKey();
    index[key]= object;
    return key;
}

But, like that, if I remove objects in index, and add new ones, there will be holes, and the key may become big.

So I would like to know if there was patterns for this kind of problem, which often appears.

Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52

1 Answers1

1

You could use an array as your index.

const index= [];

Removing an object can then be done by setting the corresponding array entry to undefined.

function removeObject(key) {
    index[key] = undefined;
    if( key == index.length - 1 ) index.pop();
}

A new object is placed in the next free slot of the array, which can be found with the indexOf method.

function addObject(object) {
    const pos = index.indexOf(undefined)
    const key = pos == -1 ? index.length : pos;
    index[key]= object;
    return key;
}

With this approach the key size will be minimal. Since array implementations are usually sparse as discussed here, also the memory usage will be as small as possible.

Community
  • 1
  • 1
user0815
  • 1,376
  • 7
  • 8