site/node_modules/hast-util-to-string/lib/index.js
2024-10-14 08:09:33 +02:00

56 lines
1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @typedef {import('hast').Nodes} Nodes
* @typedef {import('hast').Parents} Parents
*/
/**
* Get the plain-text value of a hast node.
*
* @param {Nodes} node
* Node to serialize.
* @returns {string}
* Serialized node.
*/
export function toString(node) {
// “The concatenation of data of all the Text node descendants of the context
// object, in tree order.”
if ('children' in node) {
return all(node)
}
// “Context objects data.”
return 'value' in node ? node.value : ''
}
/**
* @param {Nodes} node
* Node.
* @returns {string}
* Serialized node.
*/
function one(node) {
if (node.type === 'text') {
return node.value
}
return 'children' in node ? all(node) : ''
}
/**
* @param {Parents} node
* Node.
* @returns {string}
* Serialized node.
*/
function all(node) {
let index = -1
/** @type {Array<string>} */
const result = []
while (++index < node.children.length) {
result[index] = one(node.children[index])
}
return result.join('')
}