Эх сурвалжийг харах

Adding cache to route patterns

Shaun 2 жил өмнө
parent
commit
73924a995b
2 өөрчлөгдсөн 7 нэмэгдсэн , 4 устгасан
  1. 1 1
      package.json
  2. 6 3
      src/router.js

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "@shaun/alpinejs-router",
-  "version": "1.2.4",
+  "version": "1.2.5",
   "description": "Easy to use and flexible router for Alpine.js",
   "type": "module",
   "main": "dist/module.cjs.js",

+ 6 - 3
src/router.js

@@ -3,11 +3,12 @@ import { URLPattern } from './pattern'
 
 export class Router {
   #patterns = {}
+  #cache = {}
 
   add (route) {
     this.#patterns = {
       ...this.#patterns,
-      [route]: URLPattern.build(route)
+      [route]: this.#cache[route] ?? URLPattern.build(route)
     }
   }
 
@@ -24,7 +25,8 @@ export class Router {
 
   is (target, ...routes) {
     for (const route of routes) {
-      const pattern = this.#patterns[route] ?? URLPattern.build(route)
+      const pattern = this.#patterns[route] ?? this.#cache[route] ?? URLPattern.build(route)
+      this.#cache[route] = pattern
       if (URLPattern.is(target.path, pattern)) {
         return true
       }
@@ -34,7 +36,8 @@ export class Router {
 
   not (target, ...routes) {
     for (const route of routes) {
-      const pattern = this.#patterns[route] ?? URLPattern.build(route)
+      const pattern = this.#patterns[route] ?? this.#cache[route] ?? URLPattern.build(route)
+      this.#cache[route] = pattern
       if (URLPattern.is(target.path, pattern)) {
         return false
       }