Skip to content

Instantly share code, notes, and snippets.

@hi-ogawa
Created April 30, 2023 10:23
Show Gist options
  • Save hi-ogawa/d614758c99763cf26125085448144ea9 to your computer and use it in GitHub Desktop.
Save hi-ogawa/d614758c99763cf26125085448144ea9 to your computer and use it in GitHub Desktop.
prop-path-map.ts
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