Best way to create a hashmap in ES6 with number as index

- 1 answer

Ad

I want to build an hashmap class, or use one that comes with the language.

The index are integers. If I try to do this with an array, I see on the debugger than the size of the array is equals to the higher integer key.

Ie, if my hashmap has two elements, Map[0]= 'word1' and Map[1023]= 'word2' I can see that the array has size 1024. I'd prefer not to waste so much space.

I can't make any assumption on how the keys are distributed.

Ad

Answer

Ad

ECMAScript 6 introduces a true Map type which can be used as follows:

const m = new Map();
m.set(0, "word1");
m.set(1023, "word2");
for(const [key, value] of m) {
    console.log(key, value, typeof key);
}

Note how key is still a number - using an object literal, keys are always strings. It also provides a size property for counting key/value pairs:

const m = new Map();
m.set(0, "word1");
m.set(1023, "word2");
console.log(m.size); // 2

Babel REPL Example

Ad
source: stackoverflow.com
Ad