Skip to content

Commit

Permalink
refactor(front-matter): replace regexp objects with maps (#5379)
Browse files Browse the repository at this point in the history
  • Loading branch information
timreichen authored Jul 10, 2024
1 parent c356e39 commit adcfb5f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 20 deletions.
10 changes: 3 additions & 7 deletions front_matter/_create_extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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);
Expand Down
22 changes: 11 additions & 11 deletions front_matter/_formats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 EXTRACT_REGEXP_MAP = {
yaml: EXTRACT_YAML_REGEXP,
toml: EXTRACT_TOML_REGEXP,
json: EXTRACT_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 = new Map([
["yaml", EXTRACT_YAML_REGEXP],
["toml", EXTRACT_TOML_REGEXP],
["json", EXTRACT_JSON_REGEXP],
]);
4 changes: 2 additions & 2 deletions front_matter/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
}
Expand Down

0 comments on commit adcfb5f

Please sign in to comment.