Skip to content

Commit 14b96c6

Browse files
timreichenkt3k
andauthored
refactor(front-matter): inline recognize() (#6466)
Co-authored-by: Yoshiya Hinosawa <[email protected]>
1 parent 23358a6 commit 14b96c6

File tree

1 file changed

+5
-22
lines changed

1 file changed

+5
-22
lines changed

front_matter/any.ts

+5-22
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,10 @@ import { extract as extractToml } from "./toml.ts";
44
import { extract as extractYaml } from "./yaml.ts";
55
import { extract as extractJson } from "./json.ts";
66
import type { Extract } from "./types.ts";
7-
import type { Format } from "./test.ts";
8-
import { EXTRACT_REGEXP_MAP, RECOGNIZE_REGEXP_MAP } from "./_formats.ts";
7+
import { RECOGNIZE_REGEXP_MAP } from "./_formats.ts";
98

109
export type { Extract };
1110

12-
/**
13-
* Recognizes the format of the front matter in a string.
14-
* Supports {@link https://yaml.org | YAML}, {@link https://toml.io | TOML} and
15-
* {@link https://www.json.org/ | JSON}.
16-
*
17-
* @param str String to recognize.
18-
* @param formats A list of formats to recognize. Defaults to all supported formats.
19-
*/
20-
function recognize(
21-
str: string,
22-
formats: Format[],
23-
): Format {
24-
for (const format of formats) {
25-
if (RECOGNIZE_REGEXP_MAP.get(format)?.test(str)) return format;
26-
}
27-
throw new TypeError("Unsupported front matter format");
28-
}
29-
3011
/**
3112
* Extracts and parses {@link https://yaml.org | YAML}, {@link https://toml.io |
3213
* TOML}, or {@link https://www.json.org/ | JSON} from the metadata of front
@@ -54,14 +35,16 @@ function recognize(
5435
* @returns The extracted front matter and body content.
5536
*/
5637
export function extract<T>(text: string): Extract<T> {
57-
const formats = [...EXTRACT_REGEXP_MAP.keys()] as Format[];
58-
const format = recognize(text, formats);
38+
const format = [...RECOGNIZE_REGEXP_MAP.entries()]
39+
.find(([_, regexp]) => regexp.test(text))?.[0];
5940
switch (format) {
6041
case "yaml":
6142
return extractYaml<T>(text);
6243
case "toml":
6344
return extractToml<T>(text);
6445
case "json":
6546
return extractJson<T>(text);
47+
default:
48+
throw new TypeError("Unsupported front matter format");
6649
}
6750
}

0 commit comments

Comments
 (0)