Skip to content

Commit

Permalink
Merge pull request #89 from waxxxd/allow-for-natural-sorting
Browse files Browse the repository at this point in the history
Allow for natural sorting
  • Loading branch information
turulix authored Aug 29, 2024
2 parents d2d08b9 + 6a93d6b commit 673304f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/models/PluginSettingsTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ export enum SortBy {
// eslint-disable-next-line no-unused-vars
Alphabetically = "Alphabetically",
// eslint-disable-next-line no-unused-vars
ReverseAlphabetically = "Reverse Alphabetically"
ReverseAlphabetically = "Reverse Alphabetically",
// eslint-disable-next-line no-unused-vars
Natural = "Natural",
// eslint-disable-next-line no-unused-vars
ReverseNatural = "Reverse Natural"
}

export interface PluginSetting {
Expand Down
29 changes: 29 additions & 0 deletions src/types/MarkdownTextRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,39 @@ export class MarkdownTextRenderer {
fileTree.sort((a, b) => a.name.localeCompare(b.name))
} else if (this.plugin.settings.sortIndexFiles === SortBy.ReverseAlphabetically) {
fileTree.sort((a, b) => b.name.localeCompare(a.name))
} else if (this.plugin.settings.sortIndexFiles === SortBy.Natural) {
fileTree.sort((a, b) => this.naturalSort(a.name, b.name))
} else if (this.plugin.settings.sortIndexFiles === SortBy.ReverseNatural) {
fileTree.sort((a, b) => this.naturalSort(b.name, a.name))
}
return fileTree
}

private naturalSort(a: string, b: string): number {
const re = /(\d+)|(\D+)/g;
const aParts = a.split(re).filter((item) => item !== undefined && item.length > 0);
const bParts = b.split(re).filter((item) => item !== undefined && item.length > 0)

for (let i = 0; i < Math.min(aParts.length, bParts.length); i++) {
const aPart = aParts[i];
const bPart = bParts[i];

if (!isNaN(Number(aPart)) && !isNaN(Number(bPart))) {
const numA = Number(aPart);
const numB = Number(bPart);
if (numA !== numB) {
return numA - numB;
}
} else {
if (aPart !== bPart) {
return aPart.localeCompare(bPart);
}
}
}

return aParts.length - bParts.length;
}

private buildIndentLevel(indentLevel: number): string {
let indentText = ""
for (let j = 0; j < indentLevel; j++) {
Expand Down

0 comments on commit 673304f

Please sign in to comment.