Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 621
Snick Avatar asked Nov 29 '22 10:11

Snick


1 Answers

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

like image 180
CodingIntrigue Avatar answered Dec 10 '22 09:12

CodingIntrigue