Skip to content

Instantly share code, notes, and snippets.

@camjocotem
Last active October 25, 2024 13:49
Show Gist options
  • Select an option

  • Save camjocotem/15d8b06d4cd4229d41de514641fbc2f4 to your computer and use it in GitHub Desktop.

Select an option

Save camjocotem/15d8b06d4cd4229d41de514641fbc2f4 to your computer and use it in GitHub Desktop.
Array Dictionary
Array.prototype.toDictionary = function (keySelector, valueSelector = null) {
const dict = this.reduce((dict, item) => {
const key = keySelector(item);
dict[key] = valueSelector ? valueSelector(item) : item;
return dict;
}, {});
// Return an object that is both iterable and accessible by key
return {
...dict,
[Symbol.iterator]: function* () {
for (const key in dict) {
yield dict[key];
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment