sort example update
Vladimir Bauer
9 years ago
| 2 | 2 | import ( |
| 3 | 3 | "fmt" |
| 4 | 4 | "math/rand" |
| 5 | "sort" | |
| 5 | 6 | "sync" |
| 6 | 7 | "time" |
| 7 | 8 | |
| 12 | 13 | maxBlockSize = 12 |
| 13 | 14 | ) |
| 14 | 15 | |
| 16 | type barSlice []*mpb.Bar | |
| 17 | ||
| 18 | func (bs barSlice) Len() int { return len(bs) } | |
| 19 | ||
| 20 | func (bs barSlice) Less(i, j int) bool { | |
| 21 | is := bs[i].GetStatistics() | |
| 22 | js := bs[j].GetStatistics() | |
| 23 | ip := percentage(is.Total, is.Current, 100) | |
| 24 | jp := percentage(js.Total, js.Current, 100) | |
| 25 | return ip < jp | |
| 26 | } | |
| 27 | ||
| 28 | func (bs barSlice) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] } | |
| 29 | ||
| 30 | func sortByProgressFunc() mpb.BeforeRender { | |
| 31 | return func(bars []*mpb.Bar) { | |
| 32 | sort.Sort(sort.Reverse(barSlice(bars))) | |
| 33 | } | |
| 34 | } | |
| 35 | ||
| 36 | func percentage(total, current int64, ratio int) int { | |
| 37 | if total <= 0 { | |
| 38 | return 0 | |
| 39 | } | |
| 40 | return int(float64(ratio) * float64(current) / float64(total)) | |
| 41 | } | |
| 42 | ||
| 15 | 43 | func main() { |
| 16 | 44 | |
| 17 | 45 | var wg sync.WaitGroup |
| 18 | p := mpb.New(nil).SetWidth(60).WithSort(mpb.SortTop) | |
| 46 | p := mpb.New(nil).SetWidth(60).BeforeRenderFunc(sortByProgressFunc()) | |
| 19 | 47 | |
| 20 | 48 | name1 := "Bar#1: " |
| 21 | 49 | bar1 := p.AddBar(100). |