|
| 1 | +// Copyright 2025 Jacek Olszak |
| 2 | +// This code is licensed under MIT license (see LICENSE for details) |
| 3 | + |
| 4 | +package pimath_test |
| 5 | + |
| 6 | +import ( |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/elgopher/pi/pimath" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | +) |
| 12 | + |
| 13 | +func TestClamp(t *testing.T) { |
| 14 | + tests := map[string]struct { |
| 15 | + x, min, max int |
| 16 | + expected int |
| 17 | + }{ |
| 18 | + "lower than min": { |
| 19 | + x: -1, min: 0, max: 1, |
| 20 | + expected: 0, |
| 21 | + }, |
| 22 | + "equal to min": { |
| 23 | + x: 0, min: 0, max: 1, |
| 24 | + expected: 0, |
| 25 | + }, |
| 26 | + "greater than max": { |
| 27 | + x: 2, min: 0, max: 1, |
| 28 | + expected: 1, |
| 29 | + }, |
| 30 | + "equal to max": { |
| 31 | + x: 1, min: 0, max: 1, |
| 32 | + expected: 1, |
| 33 | + }, |
| 34 | + "between min and max": { |
| 35 | + x: 1, min: 0, max: 2, |
| 36 | + expected: 1, |
| 37 | + }, |
| 38 | + } |
| 39 | + for testName, testCase := range tests { |
| 40 | + t.Run(testName, func(t *testing.T) { |
| 41 | + actual := pimath.Clamp(testCase.x, testCase.min, testCase.max) |
| 42 | + assert.Equal(t, testCase.expected, actual) |
| 43 | + }) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func TestLerp(t *testing.T) { |
| 48 | + tests := map[string]struct { |
| 49 | + a, b, t float64 |
| 50 | + expected float64 |
| 51 | + }{ |
| 52 | + "in the middle": { |
| 53 | + a: 1, b: 2, t: 0.5, |
| 54 | + expected: 1.5, |
| 55 | + }, |
| 56 | + "beginning": { |
| 57 | + a: 1, b: 2, t: 0, |
| 58 | + expected: 1, |
| 59 | + }, |
| 60 | + "end": { |
| 61 | + a: 1, b: 2, t: 1, |
| 62 | + expected: 2, |
| 63 | + }, |
| 64 | + } |
| 65 | + for testName, testCase := range tests { |
| 66 | + t.Run(testName, func(t *testing.T) { |
| 67 | + actual := pimath.Lerp(testCase.a, testCase.b, testCase.t) |
| 68 | + assert.InDelta(t, testCase.expected, actual, 0.01) |
| 69 | + }) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +func TestDistance(t *testing.T) { |
| 74 | + tests := map[string]struct { |
| 75 | + x1, y1 float64 |
| 76 | + x2, y2 float64 |
| 77 | + expected float64 |
| 78 | + }{ |
| 79 | + "(0,0) to (2,2)": { |
| 80 | + x1: 0, y1: 0, |
| 81 | + x2: 2, y2: 2, |
| 82 | + expected: 2.83, |
| 83 | + }, |
| 84 | + "(2,2) to (0,0)": { |
| 85 | + x1: 2, y1: 2, |
| 86 | + x2: 0, y2: 0, |
| 87 | + expected: 2.83, |
| 88 | + }, |
| 89 | + } |
| 90 | + for testName, testCase := range tests { |
| 91 | + t.Run(testName, func(t *testing.T) { |
| 92 | + actual := pimath.Distance(testCase.x1, testCase.y1, testCase.x2, testCase.y2) |
| 93 | + assert.InDelta(t, testCase.expected, actual, 0.01) |
| 94 | + }) |
| 95 | + } |
| 96 | +} |
0 commit comments