simplified special cases handling in resolveByPath

main
Inga 🏳‍🌈 1 year ago
parent def5a1851e
commit 847abe3d99
  1. 28
      sitemap-parser/src/resolveByPath.ts

@ -16,26 +16,22 @@ import { Sitemap } from './types';
);
};*/
const createPaths = (
sitemap: Sitemap | null | undefined,
): [string, number][] =>
!sitemap
? []
: sitemap.children.flatMap((childNode) => [
[childNode.name, childNode.id] as [string, number],
...createPaths(childNode).map(
([path, id]) =>
[`${childNode.name}/${path}`, id] as [string, number],
),
]);
const createPaths = (node: Sitemap): Readonly<[string, number]>[] => [
['', node.id],
...node.children.flatMap((childNode) =>
createPaths(childNode).map(
([path, id]) => [`/${childNode.name}${path}`, id] as const,
),
),
];
// Second, improved implementation, where we build a static hashmap from complete paths to IDs once,
// and then use it as a single lookup table.
export const createPathResolver = (sitemap: Sitemap | null) => {
const paths = new Map(
createPaths(sitemap).map(([path, id]) => [`/${path}`, id]),
const rawPathsData = sitemap ? createPaths(sitemap) : [];
const pathsMap = new Map(
rawPathsData.map(([path, id]) => [path.length ? path : '/', id]),
);
return (path: string) =>
(path === '/' ? sitemap?.id : paths.get(path)) ?? null;
return (path: string) => pathsMap.get(path) ?? null;
};

Loading…
Cancel
Save