Files
sentinel/static/app/utils/getRouteStringFromRoutes.tsx
2024-02-15 17:01:50 +00:00

31 lines
936 B
TypeScript

import type {PlainRoute} from 'react-router';
type RouteWithPath = Omit<PlainRoute, 'path'> & Required<Pick<PlainRoute, 'path'>>;
/**
* Creates a route string from an array of `routes` from react-router
*
* It will look for the last route path that begins with a `/` and
* concatenate all of the following routes. Skips any routes without a path
*
* @param {Array<{}>} routes An array of route objects from react-router
* @return String Returns a route path
*/
export default function getRouteStringFromRoutes(routes?: PlainRoute[]): string {
if (!Array.isArray(routes)) {
return '';
}
const routesWithPaths = routes.filter((route): route is RouteWithPath => !!route.path);
const lastAbsolutePathIndex = routesWithPaths.findLastIndex(({path}) =>
path.startsWith('/')
);
return routesWithPaths
.slice(lastAbsolutePathIndex)
.filter(({path}) => !!path)
.map(({path}) => path)
.join('');
}