Created
January 12, 2020 11:38
-
-
Save folke/be929abdeb70d5ba833dda38107760cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// eslint-disable-next-line import/no-commonjs | |
var assert = require('assert'); | |
function starRegex(pattern: string) { | |
return RegExp( | |
pattern | |
.split('.') | |
.map(x => { | |
if (x === '**') return '[a-zA-Z\\.]*'; | |
if (x.includes('**')) | |
throw `Double star wildcards can only occur between dots as in request.**.expect`; | |
return x.replace('*', '[a-zA-Z]*'); | |
}) | |
.join('\\.'), | |
); | |
} | |
export function starMatch(string: string, pattern: string): boolean; | |
export function starMatch(string: string, pattern: string[]): boolean; | |
export function starMatch(string: string, pattern: string | string[]): boolean { | |
const patterns = Array.isArray(pattern) ? pattern : [pattern]; | |
for (const p of patterns) { | |
if (starRegex(p).test(string)) return true; | |
} | |
return false; | |
} | |
const test: Array<[string, string, boolean]> = [ | |
['request.get.post.expect', 'request.**.expect', true], | |
['request.get.post.expect', 'request.*.expect', false], | |
['request.get.expect', 'request.*.expect', true], | |
['request.get.expect', 'request.**.expect', true], | |
['request.get.expectSomething', 'request.**.expect*', true], | |
]; | |
for (const [string, pattern, expectedResult] of test) { | |
const result = starMatch(string, pattern); | |
console.log({ | |
string, | |
pattern, | |
regex: starRegex(pattern), | |
result, | |
}); | |
assert(result === expectedResult); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment