I have a class Rectangle
which has a prop called id
that indicates the uniqueness of that instance of Rectangle
class Rectangle {
constructor(desc) {
this.desc = desc
this.id = Symbol()
}
}
Later I need to put the id
to some other data structure and I need a quick way to look up that Rectangle
instance using the id
To achieve this I need to manually create a map e.g.
const r1 = new Rectangle('first')
const r2 = new Rectangle('second')
const r3 = new Rectangle('third')
const map = {
[r1.id]: r1,
[r2.id]: r2,
[r3.id]: r3,
}
So I can do to get the reference of r1
if I need to
map[r1.id]
I wonder if there is a programmatic way to achieve this reverse mapping where id
is the key and the Rectangle
instance is the value?
Also, I would appreciate it if someone can suggest a better name for the map - right now the name map
is not really descriptive.
Lastly, I wonder if we can get rid of id
and just use the reference of the Rectangle
instance? I know the answer is probably "it depends" but I think most of the time we would need an id
for the instances or objects. I wonder if in what circumstances using only references is not going to cut it?
from JavaScript: reverse mapping from an object id to that object
No comments:
Post a Comment