Skip to content

Commit 4e20713

Browse files
committed
Clean up code
1 parent f2809fe commit 4e20713

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

index.js

+13-14
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,20 @@ import { atom, onMount } from 'nanostores'
33
export function createRouter(routes, opts = {}) {
44
let router = atom()
55
router.routes = Object.keys(routes).map(name => {
6-
let value = routes[name]
6+
let pattern = routes[name]
77

8-
if (typeof value !== 'string') {
9-
return [name, ...[value].flat()]
8+
if (typeof pattern !== 'string') {
9+
return [name, ...[pattern].flat()]
1010
}
1111

12-
value = value.replace(/\/$/g, '') || '/'
12+
pattern = pattern.replace(/\/$/g, '') || '/'
1313

14-
let pattern = value
14+
let regexp = pattern
1515
.replace(/[\s!#$()+,.:<=?[\\\]^{|}]/g, '\\$&')
1616
.replace(/\/\\:(\w+)\\\?/g, '(?:/(?<$1>(?<=/)[^/]+))?')
1717
.replace(/\/\\:(\w+)/g, '/(?<$1>[^/]+)')
1818

19-
return [name, RegExp('^' + pattern + '$', 'i'), null, value]
19+
return [name, RegExp('^' + regexp + '$', 'i'), null, pattern]
2020
})
2121

2222
let prev
@@ -29,8 +29,8 @@ export function createRouter(routes, opts = {}) {
2929
let path = opts.search ? url.pathname + url.search : url.pathname
3030
path = path.replace(/\/($|\?)/, '$1') || '/'
3131

32-
for (let [route, pattern, callback] of router.routes) {
33-
let match = path.match(pattern)
32+
for (let [route, regexp, callback] of router.routes) {
33+
let match = path.match(regexp)
3434
if (match) {
3535
return {
3636
hash: url.hash,
@@ -71,7 +71,7 @@ export function createRouter(routes, opts = {}) {
7171
router.open(link.href)
7272
if (hashChanged) {
7373
location.hash = link.hash
74-
if (link.hash === '' || link.hash === '#') {
74+
if (!link.hash || link.hash === '#') {
7575
window.dispatchEvent(new HashChangeEvent('hashchange'))
7676
}
7777
}
@@ -135,20 +135,19 @@ export function getPagePath(router, name, params, search) {
135135
}
136136
let path = route[3]
137137
.replace(/\/:\w+\?/g, i => {
138-
let param = params ? params[i.slice(2).slice(0, -1)] : null
138+
let param = params && params[i.slice(2, -1)]
139139
if (param) {
140140
return '/' + encodeURIComponent(param)
141141
} else {
142142
return ''
143143
}
144144
})
145145
.replace(/\/:\w+/g, i => '/' + encodeURIComponent(params[i.slice(2)]))
146-
let postfix = ''
147146
if (search) {
148-
postfix = '' + new URLSearchParams(search)
149-
if (postfix) postfix = '?' + postfix
147+
let postfix = '' + new URLSearchParams(search)
148+
if (postfix) return path + '?' + postfix
150149
}
151-
return (path || '/') + postfix
150+
return path
152151
}
153152

154153
export function openPage(router, name, params, search) {

0 commit comments

Comments
 (0)