~poldi1405/go-indicators

ref: f18acc771195b3232d286362fb37b5cf038a00b0 go-indicators/progress/calculate.go -rw-r--r-- 1.5 KiB
f18acc77 — Moritz Poldrack allowed all numeric types in progress bars 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package progress

import (
	"errors"
	"fmt"
)

// GetPercentage returns the percentage of a part from a total.
func GetPercentage(parts, total interface{}) (float64, error) {
	var fparts, ftotal float64

	switch parts.(type) { // {{{ type switch for parts
	case uint8:
		fparts = float64(parts.(uint8))
	case int8:
		fparts = float64(parts.(int8))
	case uint16:
		fparts = float64(parts.(uint16))
	case int16:
		fparts = float64(parts.(int16))
	case uint32:
		fparts = float64(parts.(uint32))
	case int32:
		fparts = float64(parts.(int32))
	case uint64:
		fparts = float64(parts.(uint64))
	case int64:
		fparts = float64(parts.(int64))
	case float32:
		fparts = float64(parts.(float32))
	case float64:
		fparts = parts.(float64)
	default:
		return 0, fmt.Errorf("type %T is not supported", parts)
	} // }}}

	switch total.(type) { // {{{ type switch for total
	case uint8:
		ftotal = float64(total.(uint8))
	case int8:
		ftotal = float64(total.(int8))
	case uint16:
		ftotal = float64(total.(uint16))
	case int16:
		ftotal = float64(total.(int16))
	case uint32:
		ftotal = float64(total.(uint32))
	case int32:
		ftotal = float64(total.(int32))
	case uint64:
		ftotal = float64(total.(uint64))
	case int64:
		ftotal = float64(total.(int64))
	case float32:
		ftotal = float64(total.(float32))
	case float64:
		ftotal = total.(float64)
	default:
		return 0, fmt.Errorf("type %T is not supported", total)
	} // }}}

	if total == 0 {
		return 0, errors.New("division by zero")
	}

	return fparts / ftotal * 100, nil
}