Last active
July 7, 2022 16:38
-
-
Save LordZardeck/10827959932d8739c35815e489b53a6e to your computer and use it in GitHub Desktop.
Deep Map Get/Set
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
function deepMapGet(map, keys) { | |
return keys.reduce( | |
(resultValue, key) => | |
resultValue === undefined ? resultValue : resultValue.get(key), | |
map, | |
); | |
} |
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
function deepMapSet(map, keys, value) { | |
const levels = keys.map( | |
(key, index, { length: keyCount }) => | |
map.get(key) || (index < keyCount - 1 ? new Map() : undefined), | |
); | |
return keys.reduceRight( | |
(result, key, index) => | |
new Map([...(index > 0 ? levels[index - 1] : map), [key, result]]), | |
value, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment