Dean Tribble (via Rob Palmer) has come up with a neat trick to create constants whose values are strings with their names. With a minor change, we can use it to set up symbol-valued constants.
Setting up constants
const SymbolFactory = new Proxy({}, {
get: (_target, propKey, _receiver) => Symbol(propKey)
});
const {red, green, blue} = SymbolFactory;
assert.equal(
typeof red, 'symbol'
);
assert.equal(
String(red), 'Symbol(red)'
);
How does it work?
Each property of the pattern that object-destructures SymbolFactory, triggers a property get operation. Therefore, line B is equivalent to:
const red = SymbolFactory.red;
const green = SymbolFactory.green;
const blue = SymbolFactory.blue;
The method in line A intercepts each of these get operations. Among other information, it is provided with the key of the relevant property. It then creates and returns a symbol whose description is the property key.
Further reading
Read More