-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathtest_603_sr_loop.ts
More file actions
51 lines (48 loc) · 1.45 KB
/
test_603_sr_loop.ts
File metadata and controls
51 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class SubRouter {
match(method: string, path: string): string {
return `Sub:${method}:${path}`;
}
add(method: string, path: string, handler: any): void {}
}
class SmartRouter {
#routes: any[] | undefined = [];
#routers: SubRouter[] = [new SubRouter()];
match(method: string, path: string): string {
console.log("[SR.match] orig", method, path);
if (!this.#routes) {
throw new Error("Fatal error");
}
const routers = this.#routers;
const routes = this.#routes;
const len = routers.length;
let i = 0;
let res = "";
for (; i < len; i++) {
const router = routers[i];
try {
for (let i2 = 0; i2 < routes.length; i2++) {
router.add(routes[i2][0], routes[i2][1], routes[i2][2]);
}
res = router.match(method, path);
} catch (e) {
throw e;
}
this.match = router.match.bind(router);
this.#routers = [router];
this.#routes = void 0;
break;
}
if (i === len) {
throw new Error("Fatal error");
}
return res;
}
}
const sr = new SmartRouter();
try {
console.log("r1:", sr.match("GET", "/"));
console.log("r2:", sr.match("GET", "/x"));
console.log("r3:", sr.match("GET", "/y"));
} catch (e) {
console.log("CAUGHT:", (e as any).message);
}