refactor: sort

This commit is contained in:
Inanc Gumus
2019-10-21 12:45:12 +03:00
parent 47b24c7649
commit 0fd5c2968a
5 changed files with 38 additions and 17 deletions

View File

@ -21,8 +21,6 @@ func (l list) String() string {
return "Sorry. We're waiting for delivery 🚚.\n"
}
sort.Sort(l)
var str strings.Builder
for _, p := range l {
// fmt.Printf("* %s\n", p)
@ -39,10 +37,12 @@ func (l list) discount(ratio float64) {
}
}
// implementation of the sort.Interface:
// by default `list` sorts by `title`.
func (l list) Len() int { return len(l) }
func (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l list) Less(i, j int) bool { return l[i].title < l[j].title }
func (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
// byRelease sorts by product release dates.
type byRelease struct {
@ -50,8 +50,20 @@ type byRelease struct {
list
}
// Less takes priority over the Less method of the `list`.
// `sort.Sort` will first call this method instead of the `list`'s Less method.
func (bp byRelease) Less(i, j int) bool {
// Before() accepts a time.Time but `released` is not time.Time.
// `released.Time` is necessary.
// `Before()` accepts a `time.Time` but `released` is not `time.Time`.
return bp.list[i].released.Before(bp.list[j].released.Time)
}
/*
Anonymous embedding means auto-forwarding method calls to the embedded value:
func (bp byRelease) Len() int { return bp.list.Len() }
func (bp byRelease) Swap(i, j int) { bp.list.Swap(i, j) }
*/
func byReleaseDate(l list) sort.Interface {
return &byRelease{l}
}