Skip to content

Commit 7c30b33

Browse files
committed
Refactor code-style
* Add more docs to JSDoc * Improve performance
1 parent 3e87482 commit 7c30b33

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

lib/index.js

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
/**
2-
* @typedef {import('mdast').Root|import('mdast').Content} Node
2+
* @typedef {import('mdast').Root} Root
3+
* @typedef {import('mdast').Content} Content
34
* @typedef {import('mdast').Heading} Heading
45
*/
56

7+
/**
8+
* @typedef {Content | Root} Node
9+
*/
10+
611
import {visit} from 'unist-util-visit'
712

813
const max = 6
@@ -11,19 +16,27 @@ const max = 6
1116
* Make sure that there is only one top-level heading in the document by
1217
* adjusting headings depths accordingly.
1318
*
14-
* @template {Node} T
15-
* @param {T} tree
16-
* @returns {T}
19+
* @template {Node} Tree
20+
* Node type.
21+
* @param {Tree} tree
22+
* Tree to change.
23+
* @returns {Tree}
24+
* Given, modified, `tree`.
1725
*/
26+
// To do: next major: don’t return `tree`.
1827
export function normalizeHeadings(tree) {
19-
/** @type {boolean|undefined} */
28+
/** @type {Array<Heading>} */
29+
const all = []
30+
/** @type {boolean | undefined} */
2031
let multiple
21-
/** @type {Heading|undefined} */
32+
/** @type {Heading | undefined} */
2233
let first
23-
/** @type {Heading|undefined} */
34+
/** @type {Heading | undefined} */
2435
let title
2536

2637
visit(tree, 'heading', (node) => {
38+
all.push(node)
39+
2740
if (!first) {
2841
first = node
2942
}
@@ -44,11 +57,13 @@ export function normalizeHeadings(tree) {
4457

4558
// If there are multiple titles.
4659
if (multiple) {
47-
visit(tree, 'heading', (node) => {
48-
if (node !== title && node.depth < max) {
49-
node.depth++
60+
let index = -1
61+
while (++index < all.length) {
62+
const heading = all[index]
63+
if (heading !== title && heading.depth < max) {
64+
heading.depth++
5065
}
51-
})
66+
}
5267
}
5368

5469
return tree

0 commit comments

Comments
 (0)