]> git.scottworley.com Git - inverse-tax/blame - tax.test.js
Rename to index.html
[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
82b7a498 13function rand(limit = 99) {
9737900e
SW
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);
49188cbe 60 assert.strictEqual(invert([[10, Infinity, .1]])( 9), 9);
53d6ad33 61 assert.strictEqual(invert([[0, 100, .1], [100, Infinity, .2]])(170), 200);
b442070b 62 assert.strictEqual(invert([[0, 100, .1], [100, Infinity, .2]])(112), 127.5);
68251a4c 63 assert.strictEqual(invert([[6, 90, 0.75], [90, Infinity, 0.12]])(27), 90);
a3217513
SW
64
65 for (var i = 0; i < 1000; i++) {
66 const t = make_random_tax_table();
67 const inverted_t = invert(t);
68 for (var j = 0; j < 20; j++) {
69 const net = rand(250);
70 const gross = inverted_t(net);
71 assert.ok(near(net, gross - tax(t, gross)));
72 }
73 }
53d6ad33 74});