Skip to content

Instantly share code, notes, and snippets.

@rvighne

rvighne/multiKey.js

Last active Aug 18, 2016
Embed
What would you like to do?
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