Last active
July 6, 2021 21:53
-
-
Save rvighne/d31c57dd63a0bf1253f571389608db5a to your computer and use it in GitHub Desktop.
Create an object that has multiple keys pointing to the same value. It uses getters and setters to work its magic, but acts perfectly like a regular object, including enumeration, membership testing, and deleting properties.
This file contains 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
function multiKey(keyGroups) { | |
let obj = {}; | |
let props = {}; | |
for (let keyGroup of keyGroups) { | |
let masterKey = keyGroup[0]; | |
let prop = { | |
configurable: true, | |
enumerable: false, | |
get() { | |
return obj[masterKey]; | |
}, | |
set(value) { | |
obj[masterKey] = value; | |
} | |
}; | |
obj[masterKey] = undefined; | |
for (let i = 1; i < keyGroup.length; ++i) { | |
if (keyGroup.hasOwnProperty(i)) { | |
props[keyGroup[i]] = prop; | |
} | |
} | |
} | |
return Object.defineProperties(obj, props); | |
} | |
/* Example usage */ | |
let test = multiKey([ | |
['north', 'up'], | |
['south', 'down'], | |
['east', 'left'], | |
['west', 'right'] | |
]); | |
test.north = 42; | |
test.down = 123; | |
test.up; // returns 42 | |
test.south; // returns 123 | |
'left' in test; // true | |
'west' in test; // true | |
let count = 0; | |
for (let key in test) { | |
count += 1; | |
} | |
count === 4; // true; only unique (un-linked) properties are looped over |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment