Skip to content

Instantly share code, notes, and snippets.

@rvighne
Last active July 6, 2021 21:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rvighne/d31c57dd63a0bf1253f571389608db5a to your computer and use it in GitHub Desktop.
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.
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