Last active
January 13, 2016 01:17
-
-
Save tyler-dot-earth/7f1d0a547ff9103e2fda to your computer and use it in GitHub Desktop.
ES6 Symbols for complex keys (like addresses)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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