Skip to content

Instantly share code, notes, and snippets.

@pcattori
Last active February 9, 2023 19:15
Show Gist options
  • Save pcattori/2b47f09424c58c222bec1930fb837e77 to your computer and use it in GitHub Desktop.
Save pcattori/2b47f09424c58c222bec1930fb837e77 to your computer and use it in GitHub Desktop.
granular route update APIs for RR
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);
}
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment