Codebase list golang-github-vbauerster-mpb / 7a7b6fa
sort example update Vladimir Bauer 9 years ago
1 changed file(s) with 29 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "fmt"
44 "math/rand"
5 "sort"
56 "sync"
67 "time"
78
1213 maxBlockSize = 12
1314 )
1415
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
1543 func main() {
1644
1745 var wg sync.WaitGroup
18 p := mpb.New(nil).SetWidth(60).WithSort(mpb.SortTop)
46 p := mpb.New(nil).SetWidth(60).BeforeRenderFunc(sortByProgressFunc())
1947
2048 name1 := "Bar#1: "
2149 bar1 := p.AddBar(100).