diff --git a/src/app/home/helper.service.ts b/src/app/home/helper.service.ts index 4467009..af0f5d0 100644 --- a/src/app/home/helper.service.ts +++ b/src/app/home/helper.service.ts @@ -67,4 +67,21 @@ export class HelperService { return adjusted; } + /** + * Natural sort a list of strings, mutates array and return sorted array + * @param array + */ + public natural_sort(array) { + // using `localeCompare()` rather than implementing from scratch + // https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings + // https://fuzzytolerance.info/blog/2019/07/19/The-better-way-to-do-natural-sort-in-JavaScript/ + array.sort((a, b) => + a.localeCompare(b, navigator.languages[0] || navigator.language, { + numeric: true, + ignorePunctuation: true, + }) + ); + return array; + } + } diff --git a/src/app/home/home.component.ts b/src/app/home/home.component.ts index 3012d53..6107e7d 100644 --- a/src/app/home/home.component.ts +++ b/src/app/home/home.component.ts @@ -127,7 +127,7 @@ export class HomeComponent implements AfterViewInit, OnInit { this.electronService.ipcRenderer.send('just-started'); this.electronService.ipcRenderer.on('file-chosen', (event, filePath: string[]) => { - this.addToFileList(filePath.sort()); // sort alphabetically + this.addToFileList(this.helperService.natural_sort(filePath)); }); this.electronService.ipcRenderer.on('txt-file-updated', (event, newText: string) => { @@ -192,7 +192,7 @@ export class HomeComponent implements AfterViewInit, OnInit { } if (this.mode === 'edit') { - this.addToFileList(fileList.sort()); // sort alphabetically + this.addToFileList(this.helperService.natural_sort(fileList)); } } }