github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/sort/subsort/03-string.go (about) 1 package subsort 2 3 import "sort" 4 5 type SortedByStringVal struct { 6 IdxOrig int // index of the original slice 7 Val string // dynamically filled value to be sorted by 8 } 9 10 type sliceSortableStringAsc []SortedByStringVal 11 type sliceSortableStringDesc []SortedByStringVal 12 13 func (s sliceSortableStringAsc) Len() int { 14 return len(s) 15 } 16 17 func (s sliceSortableStringAsc) Swap(i, j int) { 18 s[i], s[j] = s[j], s[i] 19 } 20 21 func (s sliceSortableStringAsc) Less(i, j int) bool { 22 if s[i].Val < s[j].Val { 23 return true 24 } 25 return false 26 } 27 func (s sliceSortableStringDesc) Len() int { 28 return len(s) 29 } 30 31 func (s sliceSortableStringDesc) Swap(i, j int) { 32 s[i], s[j] = s[j], s[i] 33 } 34 35 func (s sliceSortableStringDesc) Less(i, j int) bool { 36 if s[i].Val > s[j].Val { 37 return true 38 } 39 return false 40 } 41 42 // 43 // A second way only requires the callee 44 // only to submit a func, that extracts the sort value by index: 45 type ExtractStringFielder func(i int) string 46 47 // 48 // An interface ExtractStringFielder, would require all callee slices to be wrapped. 49 func SortByStringValAsc(size int, f ExtractStringFielder) []SortedByStringVal { 50 51 copyOfSubset := make([]SortedByStringVal, size) 52 for i := 0; i < size; i++ { 53 copyOfSubset[i].IdxOrig = i 54 copyOfSubset[i].Val = f(i) 55 } 56 57 wrapperSortable := sliceSortableStringAsc(copyOfSubset) 58 sort.Sort(wrapperSortable) 59 unwrap := []SortedByStringVal(wrapperSortable) 60 return unwrap 61 62 } 63 func SortByStringValDesc(size int, f ExtractStringFielder) []SortedByStringVal { 64 65 copyOfSubset := make([]SortedByStringVal, size) 66 for i := 0; i < size; i++ { 67 copyOfSubset[i].IdxOrig = i 68 copyOfSubset[i].Val = f(i) 69 } 70 71 wrapperSortable := sliceSortableStringDesc(copyOfSubset) 72 sort.Sort(wrapperSortable) 73 unwrap := []SortedByStringVal(wrapperSortable) 74 return unwrap 75 76 }