-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
52 lines (39 loc) · 1.15 KB
/
index.js
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
52
const namedParam = /:\w+/g;
const splatParam = /\*\w+/g;
function stripTrailingSlash (str) {
if (str.slice(-1) === '/') {
return str.substring(0, str.length - 1);
}
return str;
}
function prepareRoute(route) {
if (!route) {
return null;
}
return stripTrailingSlash(route).replace(namedParam, '([^\/]+)').replace(splatParam, '(.*?)');
}
export default class Router {
constructor(base = '/', routes = {}) {
this.base = base;
this.routes = routes;
this.dispatch();
}
on(route, cb) {
if (!route || !cb) {
throw new Error('A route and a callback needs to be defined');
}
const formattedRoute = `^${this.base}${prepareRoute(route)}$`;
this.routes[formattedRoute] = cb;
return formattedRoute;
}
dispatchRoute(route, cb) {
const regex = new RegExp(route);
const path = prepareRoute(window.location.pathname);
if (regex.test(path)) {
cb.call(false, route, path);
}
}
dispatch() {
Object.entries(this.routes).forEach(([route, cb]) => this.dispatchRoute(route, cb));
}
}