add Min and Max functions

This commit is contained in:
Vadim Graboys 2015-07-24 07:17:22 -04:00
parent 00831300e9
commit 96d9a5e02e
2 changed files with 89 additions and 0 deletions

View file

@ -544,6 +544,40 @@ func (d *Decimal) ensureInitialized() {
} }
} }
// Returns the minimum Decimal that was passed in the arguments.
//
// To call this function with an array, you must do:
//
// Min(arr[0], arr[1:]...)
//
// This makes it harder to accidentally call Min with 0 arguments.
func Min(first Decimal, rest ...Decimal) Decimal {
ans := first
for _, item := range rest {
if item.Cmp(ans) < 0 {
ans = item
}
}
return ans
}
// Returns the maximum Decimal that was passed in the arguments.
//
// To call this function with an array, you must do:
//
// Max(arr[0], arr[1:]...)
//
// This makes it harder to accidentally call Max with 0 arguments.
func Max(first Decimal, rest ...Decimal) Decimal {
ans := first
for _, item := range rest {
if item.Cmp(ans) > 0 {
ans = item
}
}
return ans
}
func min(x, y int32) int32 { func min(x, y int32) int32 {
if x >= y { if x >= y {
return y return y

View file

@ -711,6 +711,61 @@ func TestIntPart(t *testing.T) {
} }
} }
func TestDecimal_Min(t *testing.T) {
// the first element in the array is the expected answer, rest are inputs
testCases := [][]float64{
{0, 0},
{1, 1},
{-1, -1},
{1, 1, 2},
{-2, 1, 2, -2},
{-3, 0, 2, -2, -3},
}
for _, test := range testCases {
expected, input := test[0], test[1:]
expectedDecimal := NewFromFloat(expected)
decimalInput := []Decimal{}
for _, inp := range input {
d := NewFromFloat(inp)
decimalInput = append(decimalInput, d)
}
got := Min(decimalInput[0], decimalInput[1:]...)
if !got.Equals(expectedDecimal) {
t.Errorf("Expected %v, got %v, input=%+v", expectedDecimal, got,
decimalInput)
}
}
}
func TestDecimal_Max(t *testing.T) {
// the first element in the array is the expected answer, rest are inputs
testCases := [][]float64{
{0, 0},
{1, 1},
{-1, -1},
{2, 1, 2},
{2, 1, 2, -2},
{3, 0, 3, -2},
{-2, -3, -2},
}
for _, test := range testCases {
expected, input := test[0], test[1:]
expectedDecimal := NewFromFloat(expected)
decimalInput := []Decimal{}
for _, inp := range input {
d := NewFromFloat(inp)
decimalInput = append(decimalInput, d)
}
got := Max(decimalInput[0], decimalInput[1:]...)
if !got.Equals(expectedDecimal) {
t.Errorf("Expected %v, got %v, input=%+v", expectedDecimal, got,
decimalInput)
}
}
}
// old tests after this line // old tests after this line
func TestDecimal_Scale(t *testing.T) { func TestDecimal_Scale(t *testing.T) {