As the documentation for Map says:
The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.
To take full advantage of this, I need to insert an element into a Map at a given specific order.
I know this could be done with an array, but I prefer to use a Map because I need to do a lot of lookups by key, and a Map works well for that case, while being easy to maintain.
I came up with something like this and I would like to know if there are any better ways to do it.
function insertAtIndex(index, key, value, map){
var iterator1 = map[Symbol.iterator]();
var tmpMap = new Map();
var tmpIndex=0;
for (let item of iterator1) {
if(tmpIndex === index){
tmpMap.set(key, value);
}
tmpMap.set(item[0], item[1]);
tmpIndex++;
}
return tmpMap;
}
or
insertCardAtIndex(index: Number, key: string, value:boardCard, map:Map<string, boardCard>): Map<string, boardCard> {
let clonedMap = new Map(map);
let tmpMap = new Map<string, boardCard>();
let tmpIndex = 0;
for (let entry of Array.from(clonedMap.entries())) {
if(tmpIndex === index){
tmpMap.set(key, value);
}
tmpMap.set(entry[0], entry[1]);
tmpIndex++;
}
return tmpMap;
}
For my use case, I will never have to deal with a map that is big enough to make performance a main concern, so I am willing to sacrifice performance if that makes the code more readable and maintainable.
I am using map has a "dictionary" of values by . The fact that there is no way to insert an element in a particular order makes me wonder if I should use an array instead, even though having quick lookups, and methods like .has(), .get(), and .set() that are really useful but not worth the trouble of not being able to insert at a certain index.