From: Eduardo San Martin Morote Date: Sat, 14 Dec 2019 16:31:12 +0000 (+0100) Subject: test(parser): setup score ranking X-Git-Tag: v4.0.0-alpha.0~145 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=ffae400f888ee90997e106ef1c894e050c8b7760;p=thirdparty%2Fvuejs%2Frouter.git test(parser): setup score ranking --- diff --git a/__tests__/matcher/path-ranking.spec.ts b/__tests__/matcher/path-ranking.spec.ts new file mode 100644 index 00000000..59ea5185 --- /dev/null +++ b/__tests__/matcher/path-ranking.spec.ts @@ -0,0 +1,52 @@ +import { + tokensToParser, + tokenizePath, + comparePathParser, +} from '../../src/matcher/tokenizer' + +type PathParserOptions = Parameters[1] + +describe('Path ranking', () => { + function checkPathOrder(paths: Array) { + const pathsAsStrings = paths.map(path => + typeof path === 'string' ? path : path[0] + ) + // reverse the array to force some reordering + const parsers = paths.reverse().map(path => { + const parser = + typeof path === 'string' + ? tokensToParser(tokenizePath(path)) + : tokensToParser(tokenizePath(path[0]), path[1]) + // @ts-ignore + parser.path = typeof path === 'string' ? path : path[0] + return parser + }) + + parsers.sort(comparePathParser) + + try { + expect( + parsers.map( + parser => + // @ts-ignore + parser.path + ) + ).toEqual(pathsAsStrings) + } catch (err) { + console.log( + parsers + .map( + parser => + // @ts-ignore + `${parser.path}: [${parser.score.join(', ')}]` + ) + .join('\n') + ) + throw err + } + } + + it('orders static before params', () => { + checkPathOrder(['/a', '/:id']) + }) +}) diff --git a/src/matcher/tokenizer.ts b/src/matcher/tokenizer.ts index 9b75a579..8dc34e72 100644 --- a/src/matcher/tokenizer.ts +++ b/src/matcher/tokenizer.ts @@ -187,7 +187,7 @@ interface ParamKey { interface PathParser { re: RegExp - score: number + score: number[] keys: ParamKey[] parse(path: string): Params | null stringify(params: Params): string @@ -245,7 +245,7 @@ export function tokensToParser( ...extraOptions, } - let score = 0 + let score: number[] = [] let pattern = options.start ? '^' : '' const keys: ParamKey[] = [] @@ -351,3 +351,15 @@ export function tokensToParser( stringify, } } + +export function comparePathParser(a: PathParser, b: PathParser): number { + let i = 0 + while (i < a.score.length && i < b.score.length) { + if (a.score[i] < b.score[i]) return -1 + else if (a.score[i] > b.score[i]) 1 + + i++ + } + + return 0 +}