function getRouteStringFromRoutes(routes) {
if (!Array.isArray(routes) || routes.length === 0) {
return '';
}
const routesWithPaths = routes.filter((route) => !!route.path);
let index = -1;
for (let x = routesWithPaths.length - 1; x >= 0; x--) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const route = routesWithPaths[x];
if (route.path?.startsWith('/')) {
index = x;
break;
}
}
const pathParts = routesWithPaths
.slice(index)
.filter(({ path }) => !!path)
.map(({ path }) => path);
// Join all parts with '/', then replace multiple slashes with a single one.
let fullPath = pathParts.join('/');
fullPath = fullPath.replace(/\/+/g, '/');
// Edge case: If the path started with multiple slashes and routes,
// like `//foo`, it might become `/foo`. This is generally acceptable.
return fullPath;
}
const routes = Array.from({ length: 100 }).map((_, i) => 'aaaa' + i);
console.log(getRouteStringFromRoutes(routes));
function getRouteStringFromRoutes(routes) {
if (!Array.isArray(routes) || routes.length === 0) {
return '';
}
const routesWithPaths = routes.filter((route) => !!route.path);
let index = -1;
for (let x = routesWithPaths.length - 1; x >= 0; x--) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const route = routesWithPaths[x];
if (route.path?.startsWith('/')) {
index = x;
break;
}
}
return routesWithPaths.slice(index).reduce((acc, { path }) => {
const pathSegment = acc === '/' || acc === '' ? path : `/${path}`;
return `${acc}${pathSegment}`;
}, '');
}
const routes = Array.from({ length: 100 }).map((_, i) => 'aaaa' + i);
console.log(getRouteStringFromRoutes(routes));