-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
41 lines (31 loc) · 993 Bytes
/
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
module.exports = function p2r(route) {
let hasUnnamed = true, hasNamed
if(typeof route == 'string') {
hasNamed = route.includes(':')
hasUnnamed = /[^\\][\[\*\(]/.test(route)
if(!hasNamed && !hasUnnamed) return path => path == route? {} : null
route = new RegExp('^' + route.replace(/\/:(.*?)(\??)(?=$|\/)/g, (match, param, optional) =>
optional? '(?:/(?<' + param + '>[^/]*))?' : '/(?<' + param + '>[^/]*)') + '/?$')
}
if(hasNamed && hasUnnamed) return path => {
let match = route.exec(path)
if(!match) return null
// Named and unnamed parameters
let
res = match.groups,
vals = Object.values(match.groups),
unnamed = res.unnamed = []
for(let i = 1; i < match.length; i++) {
let pos = vals.indexOf(match[i])
if(!~pos) unnamed.push(match[i])
delete vals[pos]
}
return res
}
return path => {
let match = route.exec(path)
if(!match) return null
// Named or unnamed parameters
return match.groups || {unnamed: match.slice(1)}
}
}