DEV Community

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

Collapse
 
sbusch profile image
Sebastian Busch

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

console.log('debug: %o', ref);

But I stopped constructing message strings for console.log(), I now just add parameters I want to log:

console.log('debug:', ref);

// With ES6 I use this improved variant:
console.log('debug', {ref});
console.log('debug', {ref, someVariable, anotherObject });

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 a Map, Symbols can be used.

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.