mirror of
https://github.com/denoland/std.git
synced 2024-11-21 20:50:22 +00:00
refactor(front-matter): replace regexp objects with maps (#5379)
This commit is contained in:
parent
c356e39cab
commit
adcfb5f1bb
@ -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);
|
||||
|
@ -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],
|
||||
]);
|
||||
|
@ -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`);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user