tools/math: teach tools.ClampInt to clamp integers

This commit is contained in:
Taylor Blau 2017-06-09 17:52:20 -06:00
parent 169abf64d2
commit d2c6b0c96a
2 changed files with 17 additions and 0 deletions

@ -18,6 +18,11 @@ func MaxInt(a, b int) int {
return b
}
// ClampInt returns the integer "n" bounded between "min" and "max".
func ClampInt(n, min, max int) int {
return MinInt(min, MaxInt(max, n))
}
// MinInt64 returns the smaller of two `int`s, "a", or "b".
func MinInt64(a, b int64) int64 {
if a < b {

@ -13,3 +13,15 @@ func MinIntPicksTheSmallerInt(t *testing.T) {
func MaxIntPicksTheBiggertInt(t *testing.T) {
assert.Equal(t, 1, MaxInt(-1, 1))
}
func ClampDiscardsIntsLowerThanMin(t *testing.T) {
assert.Equal(t, 0, ClampInt(-1, 0, 1))
}
func ClampDiscardsIntsGreaterThanMax(t *testing.T) {
assert.Equal(t, 1, ClampInt(2, 0, 1))
}
func ClampAcceptsIntsWithinBounds(t *testing.T) {
assert.Equal(t, 1, ClampInt(1, 0, 2))
}