Skip to content

Commit

Permalink
Build up specificity for nested routes.
Browse files Browse the repository at this point in the history
When adding an array of routes, each route will increase the
specificity instead of using only that of the last route.
  • Loading branch information
Theodore Ni committed Aug 4, 2016
1 parent 19f58bf commit 56ab65a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
11 changes: 3 additions & 8 deletions lib/route-recognizer.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,7 @@ function parse(route, names, specificity, shouldDecodes) {
// `x`, irrespective of the other parts.
// Because of this similarity, we assign each type of segment a number value written as a
// string. We can find the specificity of compound routes by concatenating these strings
// together, from left to right. After we have looped through all of the segments,
// we convert the string to a number.
specificity.val = '';

// together, from left to right.
for (var i=0; i<segments.length; i++) {
var segment = segments[i], match;

Expand All @@ -151,8 +148,6 @@ function parse(route, names, specificity, shouldDecodes) {
}
}

specificity.val = +specificity.val;

return results;
}

Expand Down Expand Up @@ -253,7 +248,7 @@ State.prototype = {
// Sort the routes by specificity
function sortSolutions(states) {
return states.sort(function(a, b) {
return b.specificity.val - a.specificity.val;
return (b.specificity.val < a.specificity.val) ? -1 : (b.specificity.val === a.specificity.val) ? 0 : 1;
});
}

Expand Down Expand Up @@ -341,7 +336,7 @@ var RouteRecognizer = function() {
RouteRecognizer.prototype = {
add: function(routes, options) {
var currentState = this.rootState, regex = "^",
specificity = {},
specificity = { val: '' },
handlers = new Array(routes.length), allSegments = [], name;

var isEmpty = true;
Expand Down
14 changes: 14 additions & 0 deletions tests/recognizer-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -889,3 +889,17 @@ test("Getting a handler for an invalid named route raises", function() {
router.handlersFor("nope");
}, /There is no route named nope/);
});

test("Matches the route with the longer static prefix", function() {
var handler1 = { handler: 1 };
var handler2 = { handler: 2 };
var router = new RouteRecognizer();

router.add([{ path: "/static", handler: handler2 }, { path: "/", handler: handler2 }]);
router.add([{ path: "/:dynamic", handler: handler1 }, { path: "/", handler: handler1 }]);

resultsMatch(router.recognize("/static"), [
{ handler: handler2, params: { }, isDynamic: false },
{ handler: handler2, params: { }, isDynamic: false }
]);
});

0 comments on commit 56ab65a

Please sign in to comment.