Andy
Andy

Reputation: 11472

JavaScript - How to implement a dictionary with keys that aren't strings

I'm trying to do a bit of simple dependency injection in my JavaScript app, so I'd like to write a function that you can pass in a class and it returns you an instance of that class from a list it's got stored.

If I have an array containing a list of tuples (class, instance) it's quite easy to do a linear search for a matching class and return the appropriate instance, but I'd rather implement it as a dictionary type. The problem is that the "key" to the dictionary is of type class (i.e. function) and JavaScript object property names can only be strings.

Is there any way to implement a dictionary with non-string keys in JavaScript, or to write some kind of function that could generate a printable name from a class function?

Upvotes: 0

Views: 195

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

You could use a Map instead, which can have keys of any type:

class C {
  prop = 'val';
}
const map = new Map();
map.set(C, new C());

console.log(map.get(C));

Note that Map lookups and retrievals are done with .get and .set calls, not with dot/bracket notation like plain objects.

Upvotes: 2

Related Questions