I have a slice of strings which contains the days of the week like this:
days := []string{"M", "Th", "W", "F", "T", "S", "Su"}
How do I sort them so it will output like this:
[M T W Th F S Su]
starting with Monday.
I have a slice of strings which contains the days of the week like this:
days := []string{"M", "Th", "W", "F", "T", "S", "Su"}
How do I sort them so it will output like this:
[M T W Th F S Su]
starting with Monday.
You can create a map keying days to their relative order. Then you can have a type implement sort.Interface
interface:
type Days []string
// map to store weekdays' relative order
var days = map[string]int{
"M": 1,
"T": 2,
"W": 3,
"Th": 4,
"F": 5,
"S": 6,
"Su": 7,
}
func (d Days) Len() int { return len(d) }
func (d Days) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d Days) Less(i, j int) bool {
return days[d[i]] < days[d[j]]
}
func main() {
ds := Days([]string{"M", "Th", "W", "F", "T", "S", "Su"})
sort.Sort(ds)
fmt.Println(ds)
}
Example: https://play.golang.org/p/lzdfI-1BJK
If you want you can move days
in Less
method to avoid globals. But that would be severely inefficient since the map will be initialized for each element of Days
.
Another implementation would be to have a pre-declared slice with the days in correct order and then use strings.Index
in Less
. This would perform slower but since your slice is of fixed length and very small (only 7 elements), it shouldn't be much of an issue.