Last active
October 25, 2024 13:49
-
-
Save camjocotem/15d8b06d4cd4229d41de514641fbc2f4 to your computer and use it in GitHub Desktop.
Array Dictionary
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
| 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