From 2f78a9d80b54bed11f467d6fedc0d08be5117766 Mon Sep 17 00:00:00 2001 From: bakonpancakz Date: Sat, 18 Jul 2026 04:22:03 -0700 Subject: [PATCH] feat: natural sorting so like numbers are in order and stuff idk black magic --- main.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 7e5ebda..8c3bc3e 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "cmp" "embed" "fmt" "io" @@ -16,6 +17,8 @@ import ( "strings" "text/template" "time" + "unicode" + "unicode/utf8" ) var ( @@ -114,6 +117,54 @@ func getEntryIcon(name string, isDir bool) string { } } +func parseNumber(s string) (num int, chars int) { + for chars < len(s) && s[chars] >= '0' && s[chars] <= '9' { + num = num*10 + int(s[chars]-'0') + chars++ + } + return +} + +func naturalCompare(a, b string) int { + + for len(a) > 0 && len(b) > 0 { + + if unicode.IsDigit(rune(a[0])) && unicode.IsDigit(rune(b[0])) { + + aValue, aSize := parseNumber(a) + bValue, bSize := parseNumber(b) + + if aValue != bValue { + if aValue < bValue { + return -1 + } + return 1 + } + + a = a[aSize:] + b = b[bSize:] + continue + } + + aRune, aSize := utf8.DecodeRuneInString(a) + bRune, bSize := utf8.DecodeRuneInString(b) + aRuneLower := unicode.ToLower(aRune) + bRuneLower := unicode.ToLower(bRune) + + if aRuneLower != bRuneLower { + if aRuneLower < bRuneLower { + return -1 + } + return 1 + } + + a = a[aSize:] + b = b[bSize:] + } + + return cmp.Compare(len(a), len(b)) +} + func init() { if serveAddress == "" { serveAddress = "127.0.0.1:8080" @@ -240,14 +291,14 @@ func main() { // Use if sortOrder == "modified" { if a.ModTime.Equal(b.ModTime) { - return strings.Compare(a.Name, b.Name) + return naturalCompare(a.Name, b.Name) } if a.ModTime.After(b.ModTime) { return -1 } return 1 } - return strings.Compare(a.Name, b.Name) + return naturalCompare(a.Name, b.Name) }) // Directory Listing