Created
August 25, 2020 19:24
-
-
Save TimVosch/6983294d0e15454fcd519d1a98f4b2bd to your computer and use it in GitHub Desktop.
Match a string against an array of allowed strings w/ wildcards (* or **)
This file contains hidden or 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
/** | |
* Matches a string (path) to an array of allowed paths which can contain wildcards | |
* returns true if there is atleast 1 full match | |
* | |
* example: | |
* matches( 'hello.world.something', [ 'not.this.one', 'hello.*.something', 'hello.**' ]); | |
* | |
* The second and last rule match and thus the string is accepted | |
* | |
* @param _path The path/string that will be checked | |
* @param _allowed The allowed strings the path will be matched against | |
*/ | |
export function matches(_path: string, _allowed: string[]): boolean { | |
// Create arrays | |
let allowed = _allowed.map((el) => el.split('.')); | |
let path = _path.split('.'); | |
let part: string; | |
while ((part = path.shift()) !== undefined) { | |
// Elimenate allowed while we have parts | |
allowed = allowed.filter((allowedParts) => { | |
const nextPart = allowedParts.shift(); | |
if (nextPart === '**') { | |
allowedParts.unshift(nextPart); | |
} | |
return nextPart === part || nextPart === '*' || nextPart === '**'; | |
}); | |
// Quit if no matches are left | |
if (allowed.length === 0) { | |
return false; | |
} | |
} | |
// | |
allowed = allowed.map((val) => (val[0] === '**' ? [] : val)); | |
// There must be atleast one full match to be true | |
return allowed.some((val) => val.length === 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment