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)
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I'd use
Symbol
as it's intended exactly for your use case.Regarding your problems with Symbols:
1. Not used in strings
Why not just write
But I stopped constructing message strings for console.log(), I now just add parameters I want to log:
2. Symbols can't be used as keys in
WeapMap
I just makes no sense to have primitive values as keys in a
WeakMap
, because they cannot be weakly referenced. That's why its forbidden.Are you sure that you need a
WeakMap
in our situation? With aMap
, Symbols can be used.Thank you for your response.
I agree with you, not being able to put a Symbol in a string interpolation isn't actually a problem.
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.
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 atoString()
implementation (just an idea: debug info like the ref number could be held in aWeakMap
if you want to hide it from the object, toString() could read from there)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.