Skip to content

Instantly share code, notes, and snippets.

@tyler-dot-earth
Last active January 13, 2016 01:17
Show Gist options
  • Save tyler-dot-earth/7f1d0a547ff9103e2fda to your computer and use it in GitHub Desktop.
Save tyler-dot-earth/7f1d0a547ff9103e2fda to your computer and use it in GitHub Desktop.
ES6 Symbols for complex keys (like addresses)
const address = 'Space Needle, 400 Broad St, Seattle, WA 98109';
const globalAddressSymbol = Symbol.for(address); // Search global Symbol registry for existing & return it, otherwise create it in the global registry.
const uniqueAddressSymbol = Symbol(address); // Creates Symbol(uniqueAddressSymbol), a guaranteed unique key.
console.log(globalAddressSymbol !== uniqueAddressSymbol); // Symbols created outside of the global registry are ALWAYS unique.
console.log(globalAddressSymbol === Symbol.for(address)); // because `Symbol.for` accesses the global Symbol registry
const addressesIndex = {
[globalAddressSymbol]: { // Address can be used as a key via Symbol (i.e. for normalization)
'prettyAddress': address,
'latLng': [47.6204, -122.3491],
},
};
console.log(addressesIndex);
console.log(addressesIndex[globalAddressSymbol]); // = { prettyAddress, latLng }
console.log(addressesIndex[Symbol(address)]); // = undefined
console.log(Symbol.keyFor(globalAddressSymbol)); // = Space Needle, 400 Broad St, Seattle, WA 98109
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment