add sort by extension

This commit is contained in:
Lilian Jónsdóttir 2024-07-15 16:10:04 -07:00
parent 746bff694c
commit 689500c942
2 changed files with 38 additions and 0 deletions

View file

@ -3,6 +3,7 @@ package files
import ( import (
"cmp" "cmp"
"strings"
"time" "time"
) )
@ -63,6 +64,16 @@ func SortByPathReverse(a, b File) int {
return cmp.Compare(b.Path(), a.Path()) return cmp.Compare(b.Path(), a.Path())
} }
func SortByExtension(a, b File) int {
aext, bext := getExts(a, b)
return cmp.Compare(aext, bext)
}
func SortByExtensionReverse(a, b File) int {
aext, bext := getExts(a, b)
return cmp.Compare(bext, aext)
}
func SortDirectoriesFirst(a, b File) int { func SortDirectoriesFirst(a, b File) int {
if !a.IsDir() && b.IsDir() { if !a.IsDir() && b.IsDir() {
return 1 return 1
@ -82,3 +93,20 @@ func SortDirectoriesLast(a, b File) int {
return 0 return 0
} }
} }
func getExts(a, b File) (string, string) {
var aext, bext string
as := strings.Split(a.Name(), ".")
bs := strings.Split(b.Name(), ".")
if len(as) <= 1 {
aext = ""
} else {
aext = as[len(as)-1]
}
if len(bs) <= 1 {
aext = ""
} else {
bext = bs[len(bs)-1]
}
return aext, bext
}

View file

@ -13,6 +13,8 @@ const (
PathReverse PathReverse
Size Size
SizeReverse SizeReverse
Extension
ExtensionReverse
Directory Directory
DirectoryReverse DirectoryReverse
) )
@ -53,6 +55,10 @@ func (s Sorting) String() string {
return "size" return "size"
case SizeReverse: case SizeReverse:
return "size (r)" return "size (r)"
case Extension:
return "extension"
case ExtensionReverse:
return "extension (r)"
case Directory: case Directory:
return "directories first" return "directories first"
case DirectoryReverse: case DirectoryReverse:
@ -80,6 +86,10 @@ func (s Sorting) Sorter() func(a, b files.File) int {
return files.SortBySize return files.SortBySize
case SizeReverse: case SizeReverse:
return files.SortBySizeReverse return files.SortBySizeReverse
case Extension:
return files.SortByExtension
case ExtensionReverse:
return files.SortByExtensionReverse
case Directory: case Directory:
return files.SortDirectoriesFirst return files.SortDirectoriesFirst
case DirectoryReverse: case DirectoryReverse: