Created
April 30, 2023 10:23
-
-
Save hi-ogawa/d614758c99763cf26125085448144ea9 to your computer and use it in GitHub Desktop.
prop-path-map.ts
This file contains 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
type PropKey = string | number; | |
type PropValue = null | undefined | number | boolean | string | Date; | |
export function toPropPathMap(input: unknown) { | |
const output = new Map<PropKey[], PropValue>(); | |
function traverse(v: unknown, keys: PropKey[]) { | |
// prettier-ignore | |
if ( | |
typeof v === "undefined" || | |
typeof v === "number" || | |
typeof v === "boolean" || | |
typeof v === "string" || | |
v === null || | |
v instanceof Date | |
) { | |
output.set(keys, null); | |
} else if (Array.isArray(v)) { | |
for (let i = 0; i < v.length; i++) { | |
traverse(v[i], [...keys, i]); | |
} | |
} else { | |
tinyassert(typeof v === "object"); | |
for (const [k, inner] of Object.entries(v)) { | |
traverse(inner, [...keys, k]); | |
} | |
} | |
} | |
traverse(input, []); | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment