Refactor micromark helper getTokenTextByType to be more efficient, remove tokenIfType helper for being redundant.

This commit is contained in:
David Anson 2024-09-16 20:50:54 -07:00
parent b749d9fbb4
commit 2ea3f95fd1
6 changed files with 82 additions and 120 deletions

View file

@ -3,7 +3,7 @@
"use strict";
const { addError, addErrorContext } = require("../helpers");
const { getTokenTextByType, tokenIfType } = require("../helpers/micromark.cjs");
const { getDescendantsByType, getTokenTextByType } = require("../helpers/micromark.cjs");
const { filterByTypesCached } = require("./cache");
// eslint-disable-next-line jsdoc/valid-types
@ -19,18 +19,16 @@ module.exports = {
const languageOnly = !!params.config.language_only;
const fencedCodes = filterByTypesCached([ "codeFenced" ]);
for (const fencedCode of fencedCodes) {
const openingFence = tokenIfType(fencedCode.children[0], "codeFencedFence");
if (openingFence) {
const { children, startLine, text } = openingFence;
const info = getTokenTextByType(children, "codeFencedFenceInfo");
if (!info) {
addErrorContext(onError, startLine, text);
} else if ((allowed.length > 0) && !allowed.includes(info)) {
addError(onError, startLine, `"${info}" is not allowed`);
}
if (languageOnly && getTokenTextByType(children, "codeFencedFenceMeta")) {
addError(onError, startLine, `Info string contains more than language: "${text}"`);
}
const openingFence = getDescendantsByType(fencedCode, [ "codeFencedFence" ])[0];
const { children, startLine, text } = openingFence;
const info = getTokenTextByType(children, "codeFencedFenceInfo");
if (!info) {
addErrorContext(onError, startLine, text);
} else if ((allowed.length > 0) && !allowed.includes(info)) {
addError(onError, startLine, `"${info}" is not allowed`);
}
if (languageOnly && getTokenTextByType(children, "codeFencedFenceMeta")) {
addError(onError, startLine, `Info string contains more than language: "${text}"`);
}
}
}