mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 12:30:49 +01:00
Suggesting Sum and Avg methods (provided unit tests), recommending removing val2 from for range loops in TestBinary & TestGobEncode (#60)
This commit is contained in:
parent
b9ab2bce74
commit
730de27aa5
2 changed files with 49 additions and 2 deletions
17
decimal.go
17
decimal.go
|
@ -828,6 +828,23 @@ func Max(first Decimal, rest ...Decimal) Decimal {
|
|||
return ans
|
||||
}
|
||||
|
||||
// Sum returns the combined total of the provided first and rest Decimals
|
||||
func Sum(first Decimal, rest ...Decimal) Decimal {
|
||||
total := first
|
||||
for _, item := range rest {
|
||||
total = total.Add(item)
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
// Avg returns the average value of the provided first and rest Decimals
|
||||
func Avg(first Decimal, rest ...Decimal) Decimal {
|
||||
count := New(int64(len(rest)+1), 0)
|
||||
sum := Sum(first, rest...)
|
||||
return sum.Div(count)
|
||||
}
|
||||
|
||||
func min(x, y int32) int32 {
|
||||
if x >= y {
|
||||
return y
|
||||
|
|
|
@ -1654,7 +1654,7 @@ func TestNullDecimal_Value(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestBinary(t *testing.T) {
|
||||
for x, _ := range testTable {
|
||||
for x := range testTable {
|
||||
|
||||
// Create the decimal
|
||||
d1 := NewFromFloat(x)
|
||||
|
@ -1689,7 +1689,7 @@ func slicesEqual(a, b []byte) bool {
|
|||
}
|
||||
|
||||
func TestGobEncode(t *testing.T) {
|
||||
for x, _ := range testTable {
|
||||
for x := range testTable {
|
||||
d1 := NewFromFloat(x)
|
||||
|
||||
b1, err := d1.GobEncode()
|
||||
|
@ -1730,3 +1730,33 @@ func TestGobEncode(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSum(t *testing.T) {
|
||||
vals := make([]Decimal, 10)
|
||||
var i = int64(0)
|
||||
|
||||
for key := range vals {
|
||||
vals[key] = New(i, 0)
|
||||
i++
|
||||
}
|
||||
|
||||
sum := Sum(vals[0], vals[1:]...)
|
||||
if !sum.Equal(New(45, 0)) {
|
||||
t.Errorf("Failed to calculate sum, expected %s got %s", New(45, 0), sum)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvg(t *testing.T) {
|
||||
vals := make([]Decimal, 10)
|
||||
var i = int64(0)
|
||||
|
||||
for key := range vals {
|
||||
vals[key] = New(i, 0)
|
||||
i++
|
||||
}
|
||||
|
||||
avg := Avg(vals[0], vals[1:]...)
|
||||
if !avg.Equal(NewFromFloat(4.5)) {
|
||||
t.Errorf("Failed to calculate average, expected %s got %s", NewFromFloat(4.5).String(), avg.String())
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue