aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDan Mayor <dmayor@digivance.com>2017-09-05 21:57:20 +0800
committerVictor Quinn <mail@victorquinn.com>2017-09-05 21:57:20 +0800
commit730de27aa507d979cb5a8a17b11c82f361c3d4a3 (patch)
treeb7c1003b3a54e13fde83445862e7977e247f4348
parentb9ab2bce742bffa417d3c01158f6062d5e05ecb4 (diff)
downloaddexon-decimal-730de27aa507d979cb5a8a17b11c82f361c3d4a3.tar.gz
dexon-decimal-730de27aa507d979cb5a8a17b11c82f361c3d4a3.tar.zst
dexon-decimal-730de27aa507d979cb5a8a17b11c82f361c3d4a3.zip
Suggesting Sum and Avg methods (provided unit tests), recommending removing val2 from for range loops in TestBinary & TestGobEncode (#60)
-rw-r--r--decimal.go17
-rw-r--r--decimal_test.go34
2 files changed, 49 insertions, 2 deletions
diff --git a/decimal.go b/decimal.go
index fd54cb5..17c8d72 100644
--- a/decimal.go
+++ b/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
diff --git a/decimal_test.go b/decimal_test.go
index 94d0db7..fc9cb12 100644
--- a/decimal_test.go
+++ b/decimal_test.go
@@ -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())
+ }
+}