Skip to content

Instantly share code, notes, and snippets.

@pcattori
Last active February 9, 2023 19:15

Revisions

  1. pcattori revised this gist Feb 9, 2023. 1 changed file with 14 additions and 0 deletions.
    14 changes: 14 additions & 0 deletions router.ts
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,17 @@
    let cloneDataRoutes = (
    routes: AgnosticDataRouteObject[]
    ): AgnosticDataRouteObject[] => {
    return routes.map((route) => {
    if (route.children === undefined) return route;
    return {
    ...route,
    children: cloneDataRoutes(route.children),
    };
    });
    };



    function addRoute(newRoute: AgnosticDataRouteObject, parentId?: string) {
    if (inFlightDataRoutes === undefined) {
    inFlightDataRoutes = cloneDataRoutes(dataRoutes);
  2. pcattori created this gist Feb 9, 2023.
    66 changes: 66 additions & 0 deletions router.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    function addRoute(newRoute: AgnosticDataRouteObject, parentId?: string) {
    if (inFlightDataRoutes === undefined) {
    inFlightDataRoutes = cloneDataRoutes(dataRoutes);
    }

    let root: AgnosticDataRouteObject = {
    id: Symbol("root").toString(),
    children: inFlightDataRoutes,
    };
    let recurse = (node: AgnosticDataRouteObject) => {
    if (node.id === parentId) {
    if (node.children === undefined) {
    node.children = [];
    }
    node.children.push(newRoute);
    return;
    }
    node.children?.forEach(recurse);
    };
    recurse(root);
    }

    function updateRoute(id: string, newRoute: AgnosticDataRouteObject) {
    if (inFlightDataRoutes === undefined) {
    inFlightDataRoutes = cloneDataRoutes(dataRoutes);
    }

    let root: AgnosticDataRouteObject = {
    id: Symbol("root").toString(),
    children: inFlightDataRoutes,
    };
    let recurse = (node: AgnosticDataRouteObject) => {
    if (node.children === undefined) return;
    let index = node.children.findIndex((child) => child.id === id);
    if (index >= 0) {
    node.children[index] = newRoute;
    return;
    }
    node.children.forEach(recurse);
    };
    recurse(root);
    }

    function deleteRoute(id: string) {
    if (inFlightDataRoutes === undefined) {
    inFlightDataRoutes = cloneDataRoutes(dataRoutes);
    }

    let root: AgnosticDataRouteObject = {
    id: Symbol("root").toString(),
    children: inFlightDataRoutes,
    };
    let recurse = (node: AgnosticDataRouteObject) => {
    if (node.children === undefined) return;
    let index = node.children.findIndex((child) => child.id === id);
    if (index >= 0) {
    node.children.splice(index, 1);
    if (node.children.length === 0) {
    node.children = undefined;
    }
    return;
    }
    node.children.forEach(recurse);
    };
    recurse(root);
    }