-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (66 loc) · 1.44 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* Mini routing system
*
* Usage:
*
* var miniroutes = require('miniroutes');
*
* var paths = [
*
* // Match '', 'search', 'search/<anything>'
* [ 'search', /^(?:search(?:\/(.+))?)?$/ ],
*
* // Match 'page2'
* [ 'page2', /^page2$/ ]
*
* ];
*
* var routing = miniroutes(paths, function(route) {
* console.log(route); // matched route
* });
*
* routing('search'); // { 'name': 'search', params: [] }
* routing('search/test'); // { 'name': 'search', params: ['test'] }
*
* Use the minihash module to feed miniroutes:
*
* var minihash = require('minihash');
* var hash = minihash('!/', routing);
*
*/
module.exports = function createRouting(paths, cb) {
var route = null;
var previous = null;
return function updatePath(path) {
previous = route;
route = getRoute(paths, path);
cb(route, previous);
};
}
function matches(re, path) {
var matches = re.exec(path);
if (matches === null) return null;
matches = matches.slice(1);
matches = matches.map(function(val) {
if (typeof val === 'undefined') return null;
return val;
});
return matches;
}
function getRoute(paths, path) {
var route = {
name: null,
params: [],
path: path
};
for (var i=0, l = paths.length, params; i < l; i++) {
// Valid path found
params = matches(paths[i][1], path);
if (params !== null) {
route.name = paths[i][0];
route.params = params;
break;
}
}
return route;
};