Created
March 28, 2021 18:34
-
-
Save stoyan-scava/d18c6b5c827e0d43942de8ca57b37993 to your computer and use it in GitHub Desktop.
Validator for file extensions
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
/** | |
* Validator of file extensions | |
*/ | |
export class ExtensionValidator { | |
private readonly detector = new ExtensionDetector(); | |
constructor() { | |
} | |
/** | |
* E.g. 'txt' from 'example.txt' | |
* @param filename | |
* @param extension extension text without a dot | |
* @param case_sensitive default:false | |
*/ | |
hasExtension(filename: string, extension: string, case_sensitive?: boolean): boolean { | |
const fileExtension = this.detector.getExtension(filename).substring(1); // removing the dot | |
if (case_sensitive) { | |
return fileExtension === extension | |
} else { | |
return filename.toLowerCase() === extension.toLowerCase(); | |
} | |
} | |
/** | |
* @return void on match. e.g. 'txt' from 'example.txt' | |
* @throws Invalid extension | |
*/ | |
check(filename: string, extension: string, case_sensitive?: boolean): void { | |
const fileExtension = this.detector.getExtension(filename); | |
if (case_sensitive) { | |
if (fileExtension === extension) return; | |
} else { | |
if (filename.toLowerCase() === extension.toLowerCase()) return; | |
} | |
throw new Error("Invalid extension"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment