@nasriya/atomix
Version:
Composable helper functions for building reliable systems
74 lines (73 loc) • 2.65 kB
JavaScript
import mimeData from "./mime-data.js";
class Mimes {
#_extensions;
#_mimes;
#_cache = {
extensionToMime: new Map(),
mimeToExtension: new Map()
};
constructor() {
const exts = new Set();
const mimes = new Set();
for (const { extension, mime } of mimeData) {
const mainMime = mime[0];
const mainExt = extension[0];
for (const ext of extension) {
exts.add(ext);
this.#_cache.extensionToMime.set(ext, mainMime);
}
for (const mimeType of mime) {
mimes.add(mimeType);
this.#_cache.mimeToExtension.set(mimeType, mainExt);
}
}
this.#_extensions = Array.from(exts);
this.#_mimes = Array.from(mimes);
}
/**
* Returns an array of all known file extensions that can be mapped to a MIME type.
* @returns {FileExtension[]} An array of file extensions.
*/
get extensions() { return this.#_extensions; }
/**
* Returns an array of all known MIME types that can be mapped to a file extension.
* @returns {Mime[]} An array of MIME types.
*/
get mimes() { return this.#_mimes; }
isValid = {
/**
* Checks if the provided extension is a valid file extension.
*
* @param ext - The extension to check.
* @returns True if the extension is valid, otherwise false.
*/
extension: (ext) => this.#_cache.extensionToMime.has(ext?.toLowerCase?.()),
/**
* Checks if the provided MIME type is a valid MIME type.
*
* @param mime - The MIME type to check.
* @returns True if the MIME type is valid, otherwise false.
*/
mime: (mime) => this.#_cache.mimeToExtension.has(mime?.toLowerCase?.())
};
/**
* Returns the file extension associated with the provided MIME type.
*
* @param mime - The MIME type to get the file extension for.
* @returns The file extension associated with the provided MIME type, or undefined if not found.
*/
getExtensionByMime(mime) {
return this.#_cache.mimeToExtension.get(mime?.toLowerCase?.());
}
/**
* Returns the MIME type associated with the provided file extension.
*
* @param ext - The file extension to get the MIME type for.
* @returns The MIME type associated with the provided file extension, or undefined if not found.
*/
getMimeByExtension(ext) {
return this.#_cache.extensionToMime.get(ext?.toLowerCase?.());
}
}
const mimes = new Mimes;
export default mimes;