Skip to content

Commit

Permalink
Merge pull request #32 from easing/main
Browse files Browse the repository at this point in the history
Fix regular expression for optional params
  • Loading branch information
ai authored Apr 9, 2024
2 parents 76d18e2 + af309f2 commit 9fd597e
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
A tiny URL router for [Nano Stores](https://github.com/nanostores/nanostores)
state manager.

* **Small.** 685 bytes (minified and brotlied). Zero dependencies.
* **Small.** 696 bytes (minified and brotlied). Zero dependencies.
* Good **TypeScript** support.
* Framework agnostic. Can be used with **React**, **Preact**, **Vue**,
**Svelte**, **Angular**, **Solid.js**, and vanilla JS.
Expand Down
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ export function createRouter(routes, opts = {}) {
let names = value.match(/(?<=\/:)\w+/g) || []
let pattern = value
.replace(/[\s!#$()+,.:<=?[\\\]^{|}]/g, '\\$&')
.replace(/\/\\:\w+\\\?/g, '/?([^/]*)')
.replace(/\/\\:\w+\\\?/g, '(?:/((?<=/)[^/]+))?')
.replace(/\/\\:\w+/g, '/([^/]+)')
return [
name,
RegExp('^' + pattern + '$', 'i'),
(...matches) =>
matches.reduce((params, match, index) => {
params[names[index]] = decodeURIComponent(match)
// match === undefined when nothing captured in regexp group
// and we swap it with empty string for backward compatibility
params[names[index]] = match ? decodeURIComponent(match) : ''
return params
}, {}),
value
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@nanostores/router",
"version": "0.14.1",
"description": "A tiny (685 bytes) router for Nano Stores state manager",
"description": "A tiny (696 bytes) router for Nano Stores state manager",
"keywords": [
"nano",
"router",
Expand Down Expand Up @@ -103,7 +103,7 @@
"import": {
"./index.js": "{ createRouter }"
},
"limit": "685 B"
"limit": "696 B"
}
],
"clean-publish": {
Expand Down
12 changes: 12 additions & 0 deletions test/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,18 @@ test('parameters can be optional', () => {
route: 'optional',
search: {}
})

changePath('/profile//')
deepStrictEqual(router.get(), undefined)

changePath('/profile///')
deepStrictEqual(router.get(), undefined)

changePath('/profile-missed-route')
deepStrictEqual(router.get(), undefined)

changePath('/profile/10/contacts/20')
deepStrictEqual(router.get(), undefined)
})

test('detects URL changes', () => {
Expand Down

0 comments on commit 9fd597e

Please sign in to comment.