Skip to content

Instantly share code, notes, and snippets.

@folke
Created Jan 12, 2020
Embed
What would you like to do?
// 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