Named capturing groups proposal
While [fixing RegExp for optional params](https://github.com/nanostores/router/pull/32) I got an idea and here is an example of how [named capturing groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group) can be used for params detection. Not sure if it should be merged or not. In general I only want to highlight a possible direction of thinking for future improvements.
This PR
* allow to define RegExp routes without callback
* removes the neediness of callbacks for string patterns (identically closures was defined for each route previously)
* provides a little bit cleaner way for params extraction from path (standard language feature used instead of fetch by index from extracted by regex parameters names array)
* reduce size by 12 bytes
---
How named capturing works:
```js
let path = "/profile/10/contacts"
let pattern = /\/profile\/(?<id>\d+)\/(?<tab>\w+)/
path.match(pattern)
[
'/profile/10/contacts',
'10',
'contacts',
index: 0,
input: '/profile/10/contacts',
groups: [Object: null prototype] { id: '10', tab: 'contacts' } // ← our desired params
]
```
Also, with named capturing groups it's possible to create links for regex routes. It's not bulletproof and production ready cause it’s impossible to handle all regex related features here, but can be used in simple cases when regex pattern contains only parameter value type checking like in example below.
```js
function regexpRouteLink(regexp, params) {
let link = regexp.source
.replace(/\\\//g, '/')
.replace(/^\^/, '')
.replace(/\$$/, '')
Object.entries(params).forEach(p => {
link = link.replace(new RegExp(`(\\(\\?<${p[0]}>[^/]*\\))`), p[1])
})
return link;
}
let regexp = /^\/profile\/(?<id>\d+)\/(?<tab>\w+)$/i
regexpRouteLink(regexp, { id: 10, tab: 'contacts' }) // => /profile/10/contacts
```
合并状态:未合并 关闭于 2024-04-17 2 条评论