summaryrefslogtreecommitdiff
path: root/src/Util/Util.test.js
blob: 9c6adbfafad5926705b3108f03267e29577c63db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { test, assert} from '../test-assert.js';
import { useAverage, clamp, lerp } from './Util.js';


test('Average correctly accumulates an average', () => {
	let [avg, avg_append] = useAverage();
	let data = [];
	for (let i=0; i<5000; i++) {
		let d = Math.random();
		data.push(d);
		avg_append(d);
	}

	let manual_average = 0;
	for (let d of data) manual_average += d;
	manual_average /= data.length;

	const precision = (decimalPlaces, num) => {
		const theta = 10**decimalPlaces;
		return Math.floor(num * theta) / theta;
	};
	assert.equal(precision(5, avg()), precision(5, manual_average));
});


test('Clamp correctly constrains values', () => {
	assert.equal(clamp(5, 0, 10), 5);
	assert.equal(clamp(-1, 0, 10), 0);
	assert.equal(clamp(15, 0, 10), 10);
});


test ('Lerp correctly interpolates values', () => {
	const a = 15;
	const b = 10;
	assert.equal(lerp(a, b, 0), a);
	assert.equal(lerp(a, b, 1), b);
	assert.equal(lerp(a, b, 0.5), (a+b)/2);
	assert.equal(lerp(a, b, 0.25), (3*a + b)/4);
	assert.equal(lerp(a, b, 0.75), (a + (3*b))/4);
});