Refactor to remove micromark helper getTokenTextByType, update getDescendantsByType to allow sub-arrays.

This commit is contained in:
David Anson 2024-09-24 22:48:14 -07:00
parent 0f210d5c1a
commit 8cbbed8e79
7 changed files with 44 additions and 94 deletions

View file

@ -451,15 +451,10 @@ function getReferenceLinkImageData(tokens) {
if (definitions.has(reference)) {
duplicateDefinitions.push([ reference, token.startLine - 1 ]);
} else {
let destinationString = null;
const parent =
micromark.getTokenParentOfType(token, [ "definition" ]);
if (parent) {
destinationString = micromark.getTokenTextByType(
micromark.filterByPredicate(parent.children),
"definitionDestinationString"
);
}
const destinationString = parent &&
micromark.getDescendantsByType(parent, [ "definitionDestination", "definitionDestinationRaw", "definitionDestinationString" ])[0]?.text;
definitions.set(
reference,
[ token.startLine - 1, destinationString ]

View file

@ -322,13 +322,15 @@ function filterByTypes(tokens, types, htmlFlow) {
* Gets a list of nested Micromark token descendants by type path.
*
* @param {Token|Token[]} parent Micromark token parent or parents.
* @param {TokenType[]} typePath Micromark token type path.
* @param {(TokenType|TokenType[])[]} typePath Micromark token type path.
* @returns {Token[]} Micromark token descendants.
*/
function getDescendantsByType(parent, typePath) {
let tokens = Array.isArray(parent) ? parent : [ parent ];
for (const type of typePath) {
tokens = tokens.flatMap((t) => t.children).filter((t) => t.type === type);
tokens = tokens
.flatMap((t) => t.children)
.filter((t) => Array.isArray(type) ? type.includes(t.type) : (type === t.type));
}
return tokens;
}
@ -459,22 +461,6 @@ function getTokenParentOfType(token, types) {
return current;
}
/**
* Get the text of the first match from a list of Micromark tokens by type.
*
* @param {Token[]} tokens Micromark tokens.
* @param {TokenType} type Type to match.
* @returns {string | null} Text of token.
*/
function getTokenTextByType(tokens, type) {
for (const token of tokens) {
if (token.type === type) {
return token.text;
}
}
return null;
}
/**
* Set containing token types that do not contain content.
*
@ -503,7 +489,6 @@ module.exports = {
getHtmlTagInfo,
getMicromarkEvents,
getTokenParentOfType,
getTokenTextByType,
inHtmlFlow,
isHtmlFlowComment,
nonContentTokens