]> git.scottworley.com Git - inverse-tax/blame - tax.test.js
Test with normalized tax tables
[inverse-tax] / tax.test.js
CommitLineData
0993d859
SW
1"use strict";
2
3var assert = require('assert');
4
5function test(description, f) {
6 f();
7}
8
a659a4f0
SW
9function near(a, b, epsilon = 1e-6) {
10 return Math.abs(a - b) < epsilon;
11}
12
9737900e
SW
13function rand(limit = 100) {
14 return Math.round(Math.random() * limit);
15}
16
a659a4f0
SW
17function make_random_tax_table() {
18 function make_random_table(min_threshold) {
19 if (rand(2)) return [];
20 const start = min_threshold === undefined ? rand() : min_threshold;
21 const end = start + 1 + rand();
22 return [[start, rand()]].concat(make_random_table(end));
23 }
24 return tax_table_from_table(make_random_table());
9737900e
SW
25}
26
0993d859
SW
27test("parse tax table", () => {
28 const parsed = parse_tax_table(' 1 2\n10 4\n');
29 assert.strictEqual(parsed.length, 2);
30 assert.deepStrictEqual(parsed[0], [1, 10, .02]);
31 assert.deepStrictEqual(parsed[1], [10, Infinity, .04]);
32});
33
34test("sum", () => {
35 assert.strictEqual(sum([]), 0);
36 assert.strictEqual(sum([7]), 7);
37 assert.strictEqual(sum([100, 1, 10]), 111);
38});
39
40test("tax", () => {
41 assert.strictEqual(tax([[10, 100, .01], [100, Infinity, .1]], 150), 5.9);
0993d859 42});
26460571
SW
43
44test("merge tax tables", () => {
26460571
SW
45 for (var i = 0; i < 1000; i++) {
46 const t1 = make_random_tax_table();
47 const t2 = make_random_tax_table();
48 const combined = merge_tax_tables(t1, t2);
49 for (var j = 0; j < 10; j++) {
50 const income = rand(250);
a659a4f0 51 assert.ok(near(tax(t1, income) + tax(t2, income), tax(combined, income)));
26460571
SW
52 }
53 }
54});
53d6ad33
SW
55
56test("invert", () => {
1c6e4069 57 assert.strictEqual(invert([ ])(10), 10);
53d6ad33
SW
58 assert.strictEqual(invert([[ 0, Infinity, .1]])( 9), 10);
59 assert.strictEqual(invert([[10, Infinity, .1]])(19), 20);
60 assert.strictEqual(invert([[0, 100, .1], [100, Infinity, .2]])(170), 200);
61});