smartsort.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package fssort
  2. /*
  3. Smart Sort
  4. Sort file based on natural string sorting logic, design to sort filename
  5. that contains digit but without zero paddings
  6. */
  7. import (
  8. "fmt"
  9. "regexp"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. )
  14. func SortNaturalFilelist(filelist []*sortBufferedStructure) []*sortBufferedStructure {
  15. filenameList := []string{}
  16. filenameMap := map[string]*sortBufferedStructure{}
  17. for _, file := range filelist {
  18. filenameList = append(filenameList, file.Filename)
  19. filenameMap[file.Filename] = file
  20. }
  21. sortedFilenameList := sortNaturalStrings(filenameList)
  22. sortedFileList := []*sortBufferedStructure{}
  23. for _, thisFilename := range sortedFilenameList {
  24. sortedFileList = append(sortedFileList, filenameMap[thisFilename])
  25. }
  26. return sortedFileList
  27. }
  28. func sortNaturalStrings(array []string) []string {
  29. bufKey := []string{}
  30. bufMap := map[string]string{}
  31. for _, thisString := range array {
  32. re := regexp.MustCompile("[0-9]+")
  33. matchings := re.FindAllString(thisString, -1)
  34. cs := thisString
  35. for _, matchPoint := range matchings {
  36. mpi, _ := strconv.Atoi(matchPoint)
  37. replacement := fmt.Sprintf("%018d", mpi)
  38. cs = strings.ReplaceAll(cs, matchPoint, replacement)
  39. }
  40. bufKey = append(bufKey, cs)
  41. bufMap[cs] = thisString
  42. }
  43. sort.Strings(bufKey)
  44. result := []string{}
  45. for _, key := range bufKey {
  46. result = append(result, bufMap[key])
  47. }
  48. return result
  49. }