i recently had a bug in my code that was due to me missing the "in insertion order" text while looking through Map object details on MDN. In short, i have a map object, lets say
let myMap = new Map;
and then, after populating it, i iterate over its contents with a simple for .. of statement. Like this
for (let [key, val] of myMap) {
...
}
The code in for loop depends on (key, value) pair to be sorted by key. However the algorithm that populates the map, does so in a random order(and i can't change that). To get around this problem, i now add all possible keys to the map object first, something like this:
let myMap = new Map;
for (let i=0; i<maxkey; ++i) myMap.set(key(i), undefined);
// And in the for loop
for (let [key, val] of myMap) {
if (typeof val === "undefined") continue;
//...
}
Fortunately, there aren't many of them(so the performance penalty is negligible), and this works. Still this solution looks a bit awkward to me.
Is there something better?