Pad/internal/browser/sort.go
Greg Pomerantz 06b1444207 gofmt: format all remaining files with the go1.27 toolchain
The tree was formatted with an older gofmt; go1.27's gofmt additionally
wants: EOF exactly one newline (no trailing blank lines), imports sorted
alphabetically within a block, mixed-precedence binary expressions
re-spaced for grouping ((a+b)/c), single-field composite literals
un-aligned, adjacent one-line method signatures aligned, and one-line
bodies containing a compound statement expanded. Applied repo-wide
(31 files under internal/); pure formatting, no semantic changes —
build and the full test suite pass.
2026-08-23 10:03:27 -04:00

72 lines
1.9 KiB
Go

package browser
import (
"sort"
"strings"
)
// SortMode defines how entries should be sorted.
type SortMode int
const (
SortModeNameAsc SortMode = iota // Name ascending (A-Z)
SortModeNameDesc // Name descending (Z-A)
SortModeDateAsc // Date ascending (oldest first)
SortModeDateDesc // Date descending (newest first)
// Total sort modes: 4
)
// sortEntries sorts entries in-place according to the given SortMode.
// Directories and files are interleaved naturally. Case-insensitive
// comparison is used for name-based sorting. Equal keys are broken
// by name (ascending).
func sortEntries(entries []Entry, mode SortMode) {
if len(entries) <= 1 {
return
}
cmp := comparator(mode)
sort.SliceStable(entries, func(i, j int) bool {
return cmp(entries[i], entries[j]) < 0
})
}
// comparator returns a comparison function for the given SortMode.
// Returns negative if a < b, zero if equal, positive if a > b.
func comparator(mode SortMode) func(a, b Entry) int {
switch mode {
case SortModeNameAsc:
return func(a, b Entry) int {
if c := strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name)); c != 0 {
return c
}
return strings.Compare(a.Name, b.Name)
}
case SortModeNameDesc:
return func(a, b Entry) int {
if c := strings.Compare(strings.ToLower(b.Name), strings.ToLower(a.Name)); c != 0 {
return c
}
return strings.Compare(b.Name, a.Name)
}
case SortModeDateAsc:
return func(a, b Entry) int {
if c := a.ModTime.Compare(b.ModTime); c != 0 {
return c
}
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
}
case SortModeDateDesc:
return func(a, b Entry) int {
if c := b.ModTime.Compare(a.ModTime); c != 0 {
return c
}
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
}
default:
// Invalid mode: no-op (preserve order)
return func(a, b Entry) int { return 0 }
}
}