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] 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', () => {