1

I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"
mbarish-me
  • 897
  • 1
  • 14
  • 25

3 Answers3

6

You could use just an object with no prototypes. For the access the key is converted to string.

var map = Object.create(null);

map['1'] = 'string one';
map[2] = 'number two';

console.log(map[1]);   // 'string one'
console.log(map['1']); // 'string one'
console.log(map);
Redu
  • 25,060
  • 6
  • 56
  • 76
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

I've created a function that gets the value from the given map. It works both ways, from string to int and from int to string.

var map = new Map();
map.set('1', 'string one');
map.set(2, 'number two');

function getFromMap(map, key){
  return map.get(key) || map.get(key.toString()) || map.get(parseInt(key));
}

console.log(getFromMap(map, 1));
console.log(getFromMap(map, '2'));
Rick
  • 1,172
  • 11
  • 25
  • This is adding a lot of complexity to each search of the map and can potentially slow down the script a lot since you are (in the worst case scenario) searching the map 3 times to find a single value ... – anteAdamovic Nov 14 '17 at 12:33
  • Correct, Nina Scholz's answer is a much better solution than this. – Rick Nov 14 '17 at 13:01
1

For starters, I would recommend that you will sanitize your keys (e.g use only strings or only numbers) and by this you will make your life easier.

If you still insist on using both type of keys you could create a wrapper function like this :

function getFromMap(map, key){
    var stringKey = key.toString(); 
    var integerKey = parseInt(key);
    return map.get(stringKey) || map.get(integerKey);
} 

As a side note : It seems that in your case you could easily use an ordinary object (Using brackets for object assignment will automatically convert the numbers to strings) :

var o = {};
o[1] = 'First value';
console.log(o[1] === o['1']); // true

For furthor reading about the advantages/disadvantages of using Map vs Objects you are invited to read the following SA question .

C'estLaVie
  • 263
  • 1
  • 3
  • 9