-
Notifications
You must be signed in to change notification settings - Fork 8
/
mapper.js
49 lines (41 loc) · 1.21 KB
/
mapper.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
module.exports = function mapper(compileFn, options) {
if (typeof compileFn !== 'function') {
throw new Error('URL Mapper - function to compile a route expected as first argument')
}
options = options || {}
var cache = {}
function getCompiledRoute(route) {
if (!cache[route]) {
cache[route] = compileFn(route, options)
}
return cache[route]
}
function parse(route, url) {
if (arguments.length < 2) throw new Error('URL Mapper - parse method expects 2 arguments')
return getCompiledRoute(route).parse(url)
}
function stringify(route, values) {
if (arguments.length < 2) throw new Error('URL Mapper - stringify method expects 2 arguments')
return getCompiledRoute(route).stringify(values)
}
function map(url, routes) {
if (arguments.length < 2) throw new Error('URL Mapper - map method expects 2 arguments')
for (var route in routes) {
var compiled = getCompiledRoute(route)
var values = compiled.parse(url)
if (values) {
var match = routes[route]
return {
route: route,
match: match,
values: values
}
}
}
}
return {
parse: parse,
stringify: stringify,
map: map
}
}