From 4204d2ea93e55ea6698e7798adf57ece5a24164a Mon Sep 17 00:00:00 2001 From: Amy Date: Mon, 30 Aug 2021 23:28:28 -0400 Subject: [PATCH] Clean up collectLeaves --- components/Navbar.tsx | 44 +++++++++++++++++++-------------- components/ShapesBackground.tsx | 6 ++++- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/components/Navbar.tsx b/components/Navbar.tsx index b4616ec7..73f13bcc 100644 --- a/components/Navbar.tsx +++ b/components/Navbar.tsx @@ -288,31 +288,37 @@ function NavItem(props: NavItemProps) { ); } -type Leaves = { +interface Leaf { name: string; route: string; exact?: boolean; ancestors: { name: string; route: string }[]; -}[]; - -function collectLeaves( - entry: { name: string; route: string; exact?: boolean; submenu?: Menu }, - ancestors: { name: string; route: string }[] -): Leaves { - if (entry.submenu == null) { - return [{ ...entry, ancestors }]; - } - const ret = [] as Leaves; - for (const subEntry of entry.submenu) { - ret.push(...collectLeaves(subEntry, [...ancestors, entry])); - } - return ret; } -const leaves: Leaves = menu.reduce((prev, cur) => { - prev.push(...collectLeaves(cur, [])); - return prev; -}, [] as Leaves); +function collectLeaves( + accumulator: Leaf[], + entry: { + name: string; + route: string; + exact?: boolean; + submenu?: Menu; + } +): Leaf[] { + if (entry.submenu == null) { + return [...accumulator, { ...entry, ancestors: [] }]; + } + + const subleaves = entry.submenu.reduce(collectLeaves, [] as Leaf[]); + return [ + ...accumulator, + ...subleaves.map((leaf) => ({ + ...leaf, + ancestors: [...leaf.ancestors, { name: entry.name, route: entry.route }], + })), + ]; +} + +const leaves: Leaf[] = menu.reduce(collectLeaves, [] as Leaf[]); function shouldHighlight( pathname: string, diff --git a/components/ShapesBackground.tsx b/components/ShapesBackground.tsx index a34a0316..0003c73d 100644 --- a/components/ShapesBackground.tsx +++ b/components/ShapesBackground.tsx @@ -45,7 +45,11 @@ export function ShapesBackground({ getConfig }: Props) { }, [getConfig, width, height, prevWidth, prevRoute, router.asPath]); return ( -
+
{Object.entries(config).map(([type, instances]) => instances.map((attributes, idx) => (