DEV Community

Discussion on: JS tip: Create debug friendly unique references using String

Collapse
 
nlepage profile image
Nicolas Lepage

Thank you for your response.

  1. I agree with you, not being able to put a Symbol in a string interpolation isn't actually a problem.

  2. I'm aware of why primitive values may not be used in a WeakMap, even if this might have appeared a little unclear in my post 😅

Yes I'm sure I need a WeakMap:

The case is an API which returns unique references, and for each of these references, some internal state is maintained by the API.

As soon as the user of the API discards a unique reference, the internal state may be garbage collected from the WeakMap.

This avoids asking from the user of the API to "release" each reference once not used anymore.

Collapse
 
sbusch profile image
Sebastian Busch

Ok, I agree with you that a WeapMap is fine here, and therefore it should IMHO be possible to have Symbols as WeakMap keys.

I just found an interesting thread at github.com/tc39/ecma262/issues/1194 (TL;DR)

Unfortunately, because of the existence of non-unique Symbols (Symbol.for()) this won't come to ECMAScript :-/

So, the best options - as you mentioned - are new String() or object/class.

The latter with a ref property for better "debugability" and/or a toString() implementation (just an idea: debug info like the ref number could be held in a WeakMap if you want to hide it from the object, toString() could read from there)

Thread Thread
 
nlepage profile image
Nicolas Lepage

Indeed interesting thread!

Too bad, I'd have prefered Symbols to be allowed as WeakMap keys...

Yes, primarily I've been using a WeakMap to hold sensitive data (which shouldn't be altered by any other way than calling the API), but it could also hold debug info.