Skip to content

Instantly share code, notes, and snippets.

@itsthatguy
Last active September 21, 2017 22:07
Show Gist options
  • Save itsthatguy/0d81581ab40a10a90d7bde2c32245e46 to your computer and use it in GitHub Desktop.
Save itsthatguy/0d81581ab40a10a90d7bde2c32245e46 to your computer and use it in GitHub Desktop.
Makes using arrays that you have zero control over easier to reference values.
var userPreferencesDict = [
'favoriteFood',
'favoriteColor',
'favoriteNumber',
];
var userPreferences = [
'pizza',
'seafoam green',
'42'
];
console.log('\n-- Dictionary 1 --------------');
function dictionary (keys, values) {
return keys.reduce((result, key, index) => {
result[key] = values[index];
return result;
}, {});
}
const preferences1 = dictionary(userPreferencesDict, userPreferences);
console.log('=> favoriteFood', preferences1.favoriteFood);
console.log('=> favoriteColor', preferences1.favoriteColor);
console.log('=> favoriteNumber', preferences1.favoriteNumber);
console.log('\n-- Dictionary 2 --------------');
function Dictionary2 (keys, values) {
this._keys = keys;
this._values = values;
this.get = (key) => {
const index = this._keys.indexOf(key);
return this._values[index];
};
return this;
}
const preferences2 = new Dictionary2(userPreferencesDict, userPreferences);
console.log('=> favoriteFood', preferences2.get('favoriteFood'));
console.log('=> favoriteColor', preferences2.get('favoriteColor'));
console.log('=> favoriteNumber', preferences2.get('favoriteNumber'));
console.log('\n-- Dictionary 3 --------------');
function Dictionary3 (dict, array) {
return new Proxy([dict, array], {
get ([keys, values], key) {
const index = keys.indexOf(key);
return values[index];
}
});
}
const preferences3 = new Dictionary3(userPreferencesDict, userPreferences);
console.log('=> favoriteFood', preferences3.favoriteFood);
console.log('=> favoriteColor', preferences3.favoriteColor);
console.log('=> favoriteNumber', preferences3.favoriteNumber);
@bigtiger
Copy link

Neat!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment