acutmore / proposal-keyby

1 stars 1 forks source link

Symbols as composite values #5

Open mhofman opened 9 months ago

mhofman commented 9 months ago

A Composite Key could be a symbol instead of an object.

Unlike objects, not all symbols are currently usable as WeakMap keys, which would make it less surprising when the author attempts to use in a weak collection a Composite Key formed only of forgeable values (#3).

Using a symbol does not automatically resolve the question of value-like or unique semantics (#2), however value semantics would be natural for symbols, and more importantly, the author may not have as high expectations for the efficiency of === with complex primitive values. After all, string comparison can already be costly today.

const obj = {};
const a = CompositeKey.for(obj, 1, 2);
const b = CompositeKey.for(obj, 1, 2);
assert(typeof a === "symbol");
assert(a === b);

const ws = new WeakSet();
ws.add(a);
assert(ws.has(b));
assert.throws(() => ws.add(CompositeKey.for(0, 1, 2)));

Unlike registered symbols, there would be no way to get the constituents out of a composite key symbol. E.g. No CompositeKey.componentsFor

ljharb commented 9 months ago

I like that - the intent could even be loosely captured in the symbol's [[SymbolDescription]].