Skip to content

Instantly share code, notes, and snippets.

@LordZardeck
Last active July 7, 2022 16:38
Show Gist options
  • Save LordZardeck/10827959932d8739c35815e489b53a6e to your computer and use it in GitHub Desktop.
Save LordZardeck/10827959932d8739c35815e489b53a6e to your computer and use it in GitHub Desktop.
Deep Map Get/Set
function deepMapGet(map, keys) {
return keys.reduce(
(resultValue, key) =>
resultValue === undefined ? resultValue : resultValue.get(key),
map,
);
}
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