Skip to content

Commit

Permalink
refactor(front-matter): call extract() functions in any.ts (#6390)
Browse files Browse the repository at this point in the history
  • Loading branch information
timreichen authored Feb 12, 2025
1 parent 01a8dfd commit e52dc6b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
29 changes: 12 additions & 17 deletions front_matter/any.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
// Copyright 2018-2025 the Deno authors. MIT license.

import { extractAndParse, type Parser, recognize } from "./_shared.ts";
import { parse as parseYaml } from "@std/yaml/parse";
import { parse as parseToml } from "@std/toml/parse";
import { recognize } from "./_shared.ts";
import { extract as extractToml } from "@std/front-matter/toml";
import { extract as extractYaml } from "@std/front-matter/yaml";
import { extract as extractJson } from "@std/front-matter/json";
import type { Extract } from "./types.ts";
import type { Format } from "./test.ts";
import { EXTRACT_REGEXP_MAP } from "./_formats.ts";

export type { Extract };

function getParserForFormat(format: Format): Parser {
switch (format) {
case "yaml":
return parseYaml as Parser;
case "toml":
return parseToml as Parser;
case "json":
return JSON.parse;
}
}

/**
* Extracts and parses {@link https://yaml.org | YAML}, {@link https://toml.io |
* TOML}, or {@link https://www.json.org/ | JSON} from the metadata of front
Expand Down Expand Up @@ -49,7 +39,12 @@ function getParserForFormat(format: Format): Parser {
export function extract<T>(text: string): Extract<T> {
const formats = [...EXTRACT_REGEXP_MAP.keys()] as Format[];
const format = recognize(text, formats);
const regexp = EXTRACT_REGEXP_MAP.get(format) as RegExp;
const parser = getParserForFormat(format);
return extractAndParse(text, regexp, parser);
switch (format) {
case "yaml":
return extractYaml<T>(text);
case "toml":
return extractToml<T>(text);
case "json":
return extractJson<T>(text);
}
}
2 changes: 1 addition & 1 deletion front_matter/toml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ export type { Extract };
* @returns The extracted TOML front matter and body content.
*/
export function extract<T>(text: string): Extract<T> {
return extractAndParse(text, EXTRACT_TOML_REGEXP, parse as Parser);
return extractAndParse<T>(text, EXTRACT_TOML_REGEXP, parse as Parser);
}

0 comments on commit e52dc6b

Please sign in to comment.