Skip to content

Instantly share code, notes, and snippets.

@folke
Created January 12, 2020 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save folke/be929abdeb70d5ba833dda38107760cc to your computer and use it in GitHub Desktop.
Save folke/be929abdeb70d5ba833dda38107760cc to your computer and use it in GitHub Desktop.
// 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