Files
shields/frontend/lib/pattern-helpers.ts
dependabot-preview[bot] 6d5a23b889 Build(deps): bump path-to-regexp from 3.1.0 to 5.0.0 (#4330)
* Build(deps): bump path-to-regexp from 3.1.0 to 5.0.0

Bumps [path-to-regexp](https://github.com/pillarjs/path-to-regexp) from 3.1.0 to 5.0.0.
- [Release notes](https://github.com/pillarjs/path-to-regexp/releases)
- [Changelog](https://github.com/pillarjs/path-to-regexp/blob/master/History.md)
- [Commits](https://github.com/pillarjs/path-to-regexp/compare/v3.1.0...v5.0.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

* chore: apply path-to-regexp v5.x changes
2019-11-16 16:27:58 -06:00

43 lines
1.3 KiB
TypeScript

import { parse } from 'path-to-regexp'
// Given a patternToRegex `pattern` with multiple-choice options like
// `foo|bar|baz`, return an array with the options. If it can't be described
// as multiple-choice options, return `undefined`.
const basicChars = /^[A-za-z0-9-]+$/
export function patternToOptions(pattern: string): string[] | undefined {
const split = pattern.split('|')
if (split.some(part => !part.match(basicChars))) {
return undefined
} else {
return split
}
}
// Removes regexp for named parameters.
export function removeRegexpFromPattern(pattern: string): string {
const tokens = parse(pattern)
const simplePattern = tokens
.map(token => {
if (typeof token === 'string') {
return token
} else {
const { delimiter, optional, repeat, name, pattern } = token
if (typeof name === 'number') {
return `${delimiter}(${pattern})`
} else {
let modifier = ''
if (optional && !repeat) {
modifier = '?'
} else if (!optional && repeat) {
modifier = '+'
} else if (optional && repeat) {
modifier = '*'
}
return `${delimiter}:${name}${modifier}`
}
}
})
.join('')
return simplePattern
}