]> git.scottworley.com Git - inverse-tax/blob - tax.test.js
b4959184215ac9b7a7c27c1a4a18f1216b5c5a3f
[inverse-tax] / tax.test.js
1 "use strict";
2
3 var assert = require('assert');
4
5 function test(description, f) {
6 f();
7 }
8
9 function near(a, b, epsilon = 1e-6) {
10 return Math.abs(a - b) < epsilon;
11 }
12
13 function rand(limit = 100) {
14 return Math.round(Math.random() * limit);
15 }
16
17 function 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());
25 }
26
27 test("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
34 test("sum", () => {
35 assert.strictEqual(sum([]), 0);
36 assert.strictEqual(sum([7]), 7);
37 assert.strictEqual(sum([100, 1, 10]), 111);
38 });
39
40 test("tax", () => {
41 assert.strictEqual(tax([[10, 100, .01], [100, Infinity, .1]], 150), 5.9);
42 });
43
44 test("merge tax tables", () => {
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);
51 assert.ok(near(tax(t1, income) + tax(t2, income), tax(combined, income)));
52 }
53 }
54 });
55
56 test("invert", () => {
57 assert.strictEqual(invert([ ])(10), 10);
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 });