From 7341907cc796ca3e84193fd2cfacc861cc6efdfe Mon Sep 17 00:00:00 2001 From: Tylor Steinberger Date: Sun, 8 May 2016 20:01:31 -0400 Subject: [PATCH 1/2] test(): explicitly opt out partial matching --- test/index.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/index.js b/test/index.js index 7c81e71..492f454 100644 --- a/test/index.js +++ b/test/index.js @@ -175,6 +175,27 @@ describe('switchPath basic usage', () => { expect(path).to.be.equal('/1736'); expect(value).to.be.equal('id is 1736'); }); + + it('should match routes explicitly using `$`', () => { + const {path, value} = switchPath('/other', { + '/': 123, + '/other/$': 456 + }) + + expect(path).to.be.equal('/other'); + expect(value).to.be.equal(456); + }) + + it('should allow opting out of partial matching for routes using `$`', () => { + const {path, value} = switchPath('/random', { + '/$': 123, + '/other': 456, + '*': 'not found route' + }); + + expect(path).to.be.equal('/random'); + expect(value).to.be.equal('not found route'); + }); }); describe('switchPath corner cases', () => { From e090c8d53e133d2e9d61331b497ca7cc11787aa6 Mon Sep 17 00:00:00 2001 From: Tylor Steinberger Date: Sun, 8 May 2016 20:02:44 -0400 Subject: [PATCH 2/2] feat(index): explicitly opt out of partial matching Using the `/$` syntax, explicitly opt-out of partial matching. Useful for having a `/` route and not having all paths match against it. --- src/index.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 358076c..f0bf273 100644 --- a/src/index.js +++ b/src/index.js @@ -76,7 +76,20 @@ function switchPath(sourcePath, routes) { let matchedPath = null let matchedValue = null - traverseRoutes(routes, function matchPattern(pattern) { + traverseRoutes(routes, function matchPattern(pattern) { // eslint-disable-line complexity, max-len + if (pattern[pattern.length - 1] === `$`) { + const realPattern = pattern.split(`/$`).join(``) + if (sourcePath.search(realPattern) === 0 && + betterMatch(pattern, matchedPath) || + sourcePath.search(realPattern + `/`) && + betterMatch(pattern, matchedPath)) + { + matchedPath = realPattern + matchedValue = routes[pattern] + } + return + } + if (sourcePath.search(pattern) === 0 && betterMatch(pattern, matchedPath)) { matchedPath = pattern matchedValue = routes[pattern]