|
1 |
| -// Stringify one nlcst node or list of nodes. |
| 1 | +/** |
| 2 | + * @typedef {import('unist').Node} Node |
| 3 | + */ |
| 4 | + |
| 5 | +/** |
| 6 | + * Stringify one nlcst node or list of nodes. |
| 7 | + * |
| 8 | + * @param {unknown} node |
| 9 | + * @param {string} [separator=''] |
| 10 | + * @returns {string} |
| 11 | + */ |
2 | 12 | export function toString(node, separator = '') {
|
3 |
| - var values |
4 |
| - var length |
| 13 | + var index = -1 |
| 14 | + /** @type {Array.<Node>} */ |
5 | 15 | var children
|
| 16 | + /** @type {Array.<string>} */ |
| 17 | + var values |
6 | 18 |
|
7 |
| - if (!node || (!('length' in node) && !node.type)) { |
| 19 | + // @ts-ignore Looks like an object. |
| 20 | + if (!node || (!Array.isArray(node) && !node.type)) { |
8 | 21 | throw new Error('Expected node, not `' + node + '`')
|
9 | 22 | }
|
10 | 23 |
|
11 |
| - if (typeof node.value === 'string') { |
12 |
| - return node.value |
13 |
| - } |
| 24 | + // @ts-ignore Looks like a literal. |
| 25 | + if (typeof node.value === 'string') return node.value |
14 | 26 |
|
| 27 | + // @ts-ignore Looks like a list of nodes or parent. |
15 | 28 | children = 'length' in node ? node : node.children
|
16 |
| - length = children.length |
17 | 29 |
|
18 | 30 | // Shortcut: This is pretty common, and a small performance win.
|
19 |
| - if (length === 1 && 'value' in children[0]) { |
| 31 | + if (children.length === 1 && 'value' in children[0]) { |
| 32 | + // @ts-ignore Looks like a literal. |
20 | 33 | return children[0].value
|
21 | 34 | }
|
22 | 35 |
|
23 | 36 | values = []
|
24 | 37 |
|
25 |
| - while (length--) { |
26 |
| - values[length] = toString(children[length], separator) |
| 38 | + while (++index < children.length) { |
| 39 | + values[index] = toString(children[index], separator) |
27 | 40 | }
|
28 | 41 |
|
29 | 42 | return values.join(separator)
|
|
0 commit comments