0

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"
alowsarwar
  • 733
  • 7
  • 22

3 Answers3

4

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
  • 19,106
  • 4
  • 44
  • 59
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
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 van Osta
  • 953
  • 9
  • 19
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
  • 183
  • 1
  • 9