refactor(front-matter): replace regexp objects with maps (#5379)

This commit is contained in:
Tim Reichen 2024-07-10 12:32:26 +02:00 committed by GitHub
parent c356e39cab
commit adcfb5f1bb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 15 additions and 19 deletions

View File

@ -30,15 +30,11 @@ function _extract<T>(
* @param str String to recognize.
* @param formats A list of formats to recognize. Defaults to all supported formats.
*/
function recognize(str: string, formats?: Format[]): Format {
if (!formats) {
formats = Object.keys(RECOGNIZE_REGEXP_MAP) as Format[];
}
function recognize(str: string, formats: Format[]): Format {
const [firstLine] = str.split(/(\r?\n)/) as [string];
for (const format of formats) {
if (RECOGNIZE_REGEXP_MAP[format].test(firstLine)) {
if (RECOGNIZE_REGEXP_MAP.get(format)?.test(firstLine)) {
return format;
}
}
@ -71,7 +67,7 @@ export function createExtractor(
const parser = formats[format];
if (!parser) throw new TypeError(`Unsupported front matter format`);
const regexp = EXTRACT_REGEXP_MAP[format];
const regexp = EXTRACT_REGEXP_MAP.get(format);
if (!regexp) throw new TypeError(`Unsupported front matter format`);
return _extract(str, regexp, parser);

View File

@ -48,14 +48,14 @@ const [RECOGNIZE_JSON_REGEXP, EXTRACT_JSON_REGEXP] = createRegExps(
],
);
export const RECOGNIZE_REGEXP_MAP = {
yaml: RECOGNIZE_YAML_REGEXP,
toml: RECOGNIZE_TOML_REGEXP,
json: RECOGNIZE_JSON_REGEXP,
} as const;
export const RECOGNIZE_REGEXP_MAP = new Map([
["yaml", RECOGNIZE_YAML_REGEXP],
["toml", RECOGNIZE_TOML_REGEXP],
["json", RECOGNIZE_JSON_REGEXP],
]);
export const EXTRACT_REGEXP_MAP = {
yaml: EXTRACT_YAML_REGEXP,
toml: EXTRACT_TOML_REGEXP,
json: EXTRACT_JSON_REGEXP,
} as const;
export const EXTRACT_REGEXP_MAP = new Map([
["yaml", EXTRACT_YAML_REGEXP],
["toml", EXTRACT_TOML_REGEXP],
["json", EXTRACT_JSON_REGEXP],
]);

View File

@ -67,10 +67,10 @@ export type { Format };
* ```
*/
export function test(str: string, formats?: Format[]): boolean {
if (!formats) formats = Object.keys(EXTRACT_REGEXP_MAP) as Format[];
if (!formats) formats = [...EXTRACT_REGEXP_MAP.keys()] as Format[];
for (const format of formats) {
const regexp = EXTRACT_REGEXP_MAP[format];
const regexp = EXTRACT_REGEXP_MAP.get(format);
if (!regexp) {
throw new TypeError(`Unable to test for ${format} front matter format`);
}