-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath-router.js
37 lines (31 loc) · 1.15 KB
/
path-router.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
export const createRouter = defaultCallback => ({
_exactRoutes: {},
_subRouters: {},
_defaultRoute: defaultCallback
});
export const setExactRoute = (router, pathname, callback) => {
router._exactRoutes[pathname] = callback;
};
export const setSubRouter = (router, subPath, subRouter) => {
router._subRouters[subPath] = subRouter;
};
export const findRoute = (router, pathname) => {
if (pathname in router._exactRoutes) {
return fullPath => router._exactRoutes[pathname]('', fullPath);
}
const subrouterMatches = Object.keys(router._subRouters)
.filter(p => pathname.startsWith(p))
.sort((a, b) => b.length - a.length);
for (const subrouterPath of subrouterMatches) {
const subrouter = router._subRouters[subrouterPath];
const tailPath = pathname.replace(subrouterPath, '');
const callback = findRoute(subrouter, tailPath);
if (callback) {
return callback;
}
}
if (router._defaultRoute) {
return fullPath => router._defaultRoute(pathname, fullPath);
}
};
export const executeRoute = (router, pathname) => findRoute(router, pathname)(pathname);