-
-
Save nickpresta/5614640 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package math | |
import ( | |
"errors" | |
m "math" | |
) | |
// Finds the minimum value in a slice of numbers | |
func Min(xs []float64) (float64, error) { | |
if len(xs) == 0 { | |
return m.NaN(), errors.New("Cannot get minimum value from empty slice") | |
} | |
min := xs[0] | |
for _, v := range xs { | |
if v < min { | |
min = v | |
} | |
} | |
return min, nil | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package math | |
import ( | |
m "math" | |
"testing" | |
) | |
type testpair struct { | |
values []float64 | |
min float64 | |
} | |
var minTests = []testpair{ | |
{[]float64{1, 2}, 1}, | |
{[]float64{1, 1, 1, 1, 1, 1}, 1}, | |
{[]float64{-1, 1}, -1}, | |
} | |
var minTestsNaN = []testpair{ | |
{[]float64{}, m.NaN()}, | |
} | |
func TestMin(t *testing.T) { | |
for _, pair := range minTests { | |
if v, err := Min(pair.values); err != nil { | |
t.Error("Got unexpected error: ", err) | |
} else if v != pair.min { | |
t.Error( | |
"For", pair.values, | |
"expected", pair.min, | |
"got", v, | |
) | |
} | |
} | |
} | |
func TestMinNaN(t *testing.T) { | |
for _, pair := range minTestsNaN { | |
v, err := Min(pair.values) | |
if err != nil { | |
if !m.IsNaN(v) { | |
t.Error("Should return NaN") | |
} | |
} else { | |
t.Error("Should've got error for NaN") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
math.NaN
doesn't compare to anything (including itself) so I would separate out the test case and use an error to notify people when they get back a non-float64 return value (which they can check usingIsNaN
or whatever)