Skip to content

Commit

Permalink
memoize fields for repeated children
Browse files Browse the repository at this point in the history
  • Loading branch information
nedredmond committed Jan 15, 2024
1 parent 152484f commit f1c4ec2
Showing 1 changed file with 53 additions and 33 deletions.
86 changes: 53 additions & 33 deletions src/routes/wcag-routes.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,58 @@
import type { RouteObject } from "react-router-dom";
import type { WcagResponseData } from "../types";
import type { WcagItem, WcagResponseData } from "../types";
import { pathAliases } from "../types";
import { parse } from "../utils";
import loader from "./loaders/wcag-loader";

export const wcagRoutes = (wcag: WcagResponseData): RouteObject[] => [
{
path: "wcag2",
loader: () => loader(),
children: [
...wcag.principles
.map((principle): RouteObject[] =>
pathAliases.map((pKey) => ({
path: `${parse(principle[pKey])}`,
loader: () => loader(principle),
children: principle.guidelines
.map((guideline): RouteObject[] =>
pathAliases.map((gKey) => ({
path: `${parse(guideline[gKey])}`,
loader: () => loader(guideline),
children: guideline.successcriteria
.map((successcriterion): RouteObject[] =>
pathAliases.map((scKey) => ({
path: `${parse(successcriterion[scKey])}`,
loader: () => loader(successcriterion),
})),
)
.flat(),
})),
)
.flat(),
})),
)
.flat(),
],
},
];
interface RouteFields {
path: string;
loader: () => Response;
}

export const wcagRoutes = (wcag: WcagResponseData) => {
const routeFieldsMap = new Map<[WcagItem, keyof WcagItem], RouteFields>();

const routeFields = (item: WcagItem, key: keyof WcagItem) => {
const cached = routeFieldsMap.get([item, key]);
if (cached) return cached;

const route = {
path: parse(item[key]),
loader: () => loader(item),
};

routeFieldsMap.set([item, key], route);

return route;
};

return [
{
path: "wcag2",
loader: () => loader(),
children: [
...wcag.principles
.map((principle): RouteObject[] =>
pathAliases.map((pKey) => ({
...routeFields(principle, pKey),
children: principle.guidelines
.map((guideline): RouteObject[] =>
pathAliases.map((gKey) => ({
...routeFields(guideline, gKey),
children: guideline.successcriteria
.map((successcriterion): RouteObject[] =>
pathAliases.map((scKey) => ({
...routeFields(successcriterion, scKey),
})),
)
.flat(),
})),
)
.flat(),
})),
)
.flat(),
],
},
];
};

0 comments on commit f1c4ec2

Please sign in to comment.