Last active
September 21, 2017 22:07
-
-
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.
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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat!