UNPKG

cranker-router

Version:
54 lines (43 loc) 1.55 kB
// How router path mapping works - see the test-mapping.js file const longestPathFirst = function (path) { return path .substring(1) .split("/") .reverse() .reduce((a,o,i,arr) => { const targetPath = arr.slice(i).reverse().join("/"); if (i === arr.length - 1 && targetPath === "") { return a; } return a.concat([targetPath]); }, []) .concat(["/"]); }; const pathMatch = function (path, routeList, next) { const candidateMatchPaths = path === "/" ? [path] : longestPathFirst(path); if (candidateMatchPaths === null) { return next(); } let routePath; let wsList; for (const routablePath of candidateMatchPaths) { const matchedPath = Object.keys(routeList) // Find the longest path with an indexOf match .filter(route => route.indexOf(routablePath) === 0) .map(route => [route, route.length]) .sort(([pathA, lenA], [pathB, lenB]) => lenA < lenB ? -1 : lenA > lenB ? 1 : 0) .reverse() .slice(0,1) .map(([path, len]) => path); if (matchedPath !== undefined || matchedPath.length === 1) { routePath = matchedPath[0]; wsList = routeList[routePath]; if (wsList !== undefined) { break; } } } return {routePath, wsList}; }; exports.longestPathFirst = longestPathFirst; exports.pathMatch = pathMatch; // End