Split out maths functions into maths, vector and bearing

This commit is contained in:
Marc Di Luzio 2020-06-09 18:08:07 +01:00
parent aae668fb57
commit 51fe918090
14 changed files with 335 additions and 273 deletions

41
pkg/maths/maths.go Normal file
View file

@ -0,0 +1,41 @@
package maths
// Abs gets the absolute value of an int
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
// pmod is a mositive modulo
// golang's % is a "remainder" function si misbehaves for negative modulus inputs
func Pmod(x, d int) int {
if x == 0 || d == 0 {
return 0
}
x = x % d
if x >= 0 {
return x
} else if d < 0 {
return x - d
} else {
return x + d
}
}
// Max returns the highest int
func Max(x int, y int) int {
if x < y {
return y
}
return x
}
// Min returns the lowest int
func Min(x int, y int) int {
if x > y {
return y
}
return x
}

33
pkg/maths/maths_test.go Normal file
View file

@ -0,0 +1,33 @@
package maths
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAbs(t *testing.T) {
assert.Equal(t, 0, Abs(0))
assert.Equal(t, 1, Abs(1))
assert.Equal(t, 1, Abs(-1))
}
func TestPmod(t *testing.T) {
assert.Equal(t, 0, Pmod(0, 0))
assert.Equal(t, 2, Pmod(6, 4))
assert.Equal(t, 2, Pmod(-6, 4))
assert.Equal(t, 4, Pmod(-6, 10))
}
func TestMax(t *testing.T) {
assert.Equal(t, 500, Max(100, 500))
assert.Equal(t, 1, Max(-4, 1))
assert.Equal(t, -2, Max(-4, -2))
}
func TestMin(t *testing.T) {
assert.Equal(t, 100, Min(100, 500))
assert.Equal(t, -4, Min(-4, 1))
assert.Equal(t, -4, Min(-4, -2))
}