const paramRe = /^:(.+)/ ; const SEGMENT_POINTS = 4 ; const STATIC_POINTS = 3 ; const DYNAMIC_POINTS = 2 ; const SPLAT_PENALTY = 1 ; const ROOT_POINTS = 1 ; const isRootSegment = ( segment ) => segment === '' ; const isDynamic = ( segment ) => paramRe . test ( segment ) ; const isSplat = ( segment ) => segment && segment [ 0 ] === '*' ; const segmentize = ( uri ) => uri . replace ( /(^\/+|\/+$)/g , '' ) . split ( '/' ) ; export const rankRoute = ( route , index ) => { const { fromPath } = route ; const routeScore = segmentize ( fromPath ) . reduce ( ( score , segment ) => { score += SEGMENT_POINTS ; if ( isRootSegment ( segment ) ) score += ROOT_POINTS ; else if ( isDynamic ( segment ) ) score += DYNAMIC_POINTS ; else if ( isSplat ( segment ) ) score -= SEGMENT_POINTS + SPLAT_PENALTY ; else score += STATIC_POINTS ; return score ; } , 0 ) ; return { route , score : routeScore , index } ; } ; export const rankRoutes = ( routes ) => routes . map ( rankRoute ) . sort ( ( a , b ) => a . score < b . score ? 1 : a . score > b . score ? - 1 : a . index - b . index ) . map ( ( { route } ) => route ) ;