Skip to content

Commit

Permalink
Merge pull request #184 from mjbvz/recurse-build-toc
Browse files Browse the repository at this point in the history
Use loop instead of recursion
  • Loading branch information
mjbvz authored May 22, 2024
2 parents 50b665a + 84c4364 commit 7156aba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
35 changes: 18 additions & 17 deletions src/languageFeatures/documentSymbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,27 +88,28 @@ export class MdDocumentSymbolProvider {
};
}

#buildTocSymbolTree(parent: MarkdownSymbol, entries: readonly TocEntry[], additionalSymbols: lsp.DocumentSymbol[]): void {
if (entries.length) {
while (additionalSymbols.length && isBefore(additionalSymbols[0].range.end, entries[0].sectionLocation.range.start)) {
#buildTocSymbolTree(root: MarkdownSymbol, entries: readonly TocEntry[], additionalSymbols: lsp.DocumentSymbol[]): void {
let parent: MarkdownSymbol | undefined = root;
for (const entry of entries) {
while (additionalSymbols.length && isBefore(additionalSymbols[0].range.end, entry.sectionLocation.range.start)) {
parent.children.push(additionalSymbols.shift()!);
}
}

if (!entries.length) {
return;
}

const entry = entries[0];
const symbol = this.#tocToDocumentSymbol(entry);
symbol.children = [];

while (parent && entry.level <= parent.level) {
parent = parent.parent;
}
if (!parent) {
// Should not happen
return;
}

while (entry.level <= parent.level) {
parent = parent.parent!;
const symbol = this.#tocToDocumentSymbol(entry);
symbol.children = [];
parent.children.push(symbol);

parent = { level: entry.level, children: symbol.children, parent, range: entry.sectionLocation.range };
}
parent.children.push(symbol);

this.#buildTocSymbolTree({ level: entry.level, children: symbol.children, parent, range: entry.sectionLocation.range }, entries.slice(1), additionalSymbols);
}

#tocToDocumentSymbol(entry: TocEntry): lsp.DocumentSymbol {
Expand Down
2 changes: 1 addition & 1 deletion src/test/documentSymbols.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ interface ExpectedDocSymbol {
}

function assertDocumentSymbolsEqual(actual: readonly lsp.DocumentSymbol[], expected: ReadonlyArray<ExpectedDocSymbol>, path = '') {
assert.strictEqual(actual.length, expected.length, 'Link counts to be equal');
assert.strictEqual(actual.length, expected.length, 'Symbol counts to be equal');

for (let i = 0; i < actual.length; ++i) {
const exp = expected[i];
Expand Down

0 comments on commit 7156aba

Please sign in to comment.