-
Notifications
You must be signed in to change notification settings - Fork 89
/
naturalsort.go
95 lines (82 loc) · 2 KB
/
naturalsort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package utils
import (
"fmt"
"sort"
"strconv"
"unicode"
)
// SortStringsNaturally sorts strings according to their natural sort order.
func SortStringsNaturally(s []string) []string {
sort.Sort(naturally(s))
return s
}
type naturally []string
func (n naturally) Len() int {
return len(n)
}
func (n naturally) Swap(a, b int) {
n[a], n[b] = n[b], n[a]
}
// Less sorts by non-numeric prefix and numeric suffix
// when one exists.
func (n naturally) Less(a, b int) bool {
aVal := n[a]
bVal := n[b]
for {
// If bVal is empty, then aVal can't be less than it.
if bVal == "" {
return false
}
// If aVal is empty here, then is must be less than bVal.
if aVal == "" {
return true
}
aPrefix, aNumber, aRemainder := splitAtNumber(aVal)
bPrefix, bNumber, bRemainder := splitAtNumber(bVal)
if aPrefix != bPrefix {
return aPrefix < bPrefix
}
if aNumber != bNumber {
return aNumber < bNumber
}
// Everything is the same so far, try again with the remainer.
aVal = aRemainder
bVal = bRemainder
}
}
// splitAtNumber splits given string at the first digit, returning the
// prefix before the number, the integer represented by the first
// series of digits, and the remainder of the string after the first
// series of digits. If no digits are present, the number is returned
// as -1 and the remainder is empty.
func splitAtNumber(str string) (string, int, string) {
i := indexOfDigit(str)
if i == -1 {
// no numbers
return str, -1, ""
}
j := i + indexOfNonDigit(str[i:])
n, err := strconv.Atoi(str[i:j])
if err != nil {
panic(fmt.Sprintf("parsing number %v: %v", str[i:j], err)) // should never happen
}
return str[:i], n, str[j:]
}
func indexOfDigit(str string) int {
for i, rune := range str {
if unicode.IsDigit(rune) {
return i
}
}
return -1
}
func indexOfNonDigit(str string) int {
for i, rune := range str {
if !unicode.IsDigit(rune) {
return i
}
}
return len(str)
}