]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
test(parser): setup score ranking
authorEduardo San Martin Morote <posva13@gmail.com>
Sat, 14 Dec 2019 16:31:12 +0000 (17:31 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Wed, 18 Dec 2019 09:26:15 +0000 (10:26 +0100)
__tests__/matcher/path-ranking.spec.ts [new file with mode: 0644]
src/matcher/tokenizer.ts

diff --git a/__tests__/matcher/path-ranking.spec.ts b/__tests__/matcher/path-ranking.spec.ts
new file mode 100644 (file)
index 0000000..59ea518
--- /dev/null
@@ -0,0 +1,52 @@
+import {
+  tokensToParser,
+  tokenizePath,
+  comparePathParser,
+} from '../../src/matcher/tokenizer'
+
+type PathParserOptions = Parameters<typeof tokensToParser>[1]
+
+describe('Path ranking', () => {
+  function checkPathOrder(paths: Array<string | [string, PathParserOptions]>) {
+    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'])
+  })
+})
index 9b75a57914e0a6dff1afb149588e8159aaf1b0f3..8dc34e726bd261244dd7a8c9106c45f022ad12b3 100644 (file)
@@ -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
+}