Files
learngo/interfaces/11-sort/list.go

58 lines
1.3 KiB
Go
Raw Normal View History

2019-10-17 14:11:51 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"sort"
"strings"
)
// product is now *product because sorting will unnecessarily copy the product values
type list []*product
func (l list) String() string {
if len(l) == 0 {
return "Sorry. We're waiting for delivery 🚚.\n"
}
sort.Sort(l)
2019-10-17 20:23:45 +03:00
2019-10-17 14:11:51 +03:00
var str strings.Builder
for _, p := range l {
2019-10-17 20:23:45 +03:00
// fmt.Printf("* %s\n", p)
str.WriteString("* ")
str.WriteString(p.String())
str.WriteRune('\n')
2019-10-17 14:11:51 +03:00
}
return str.String()
}
func (l list) discount(ratio float64) {
for _, p := range l {
p.discount(ratio)
}
}
// 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 }
// byRelease sorts by product release dates.
type byRelease struct {
// byRelease embeds `list` and reuses list's Len and Swap methods.
list
}
func (bp byRelease) Less(i, j int) bool {
// Before() accepts a time.Time but `released` is not time.Time.
// `released.Time` is necessary.
return bp.list[i].released.Before(bp.list[j].released.Time)
}