]>
git.scottworley.com Git - inverse-tax/blob - tax.test.js
3 var assert
= require('assert');
5 function test(description
, f
) {
9 function near(a
, b
, epsilon
= 1e-6) {
10 return Math
.abs(a
- b
) < epsilon
;
13 function rand(limit
= 99) {
14 return Math
.round(Math
.random() * limit
);
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
));
24 return tax_table_from_table(make_random_table());
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]);
35 assert
.strictEqual(sum([]), 0);
36 assert
.strictEqual(sum([7]), 7);
37 assert
.strictEqual(sum([100, 1, 10]), 111);
41 assert
.strictEqual(tax([[10, 100, .01], [100, Infinity
, .1]], 150), 5.9);
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
)));
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([[10, Infinity
, .1]])( 9), 9);
61 assert
.strictEqual(invert([[0, 100, .1], [100, Infinity
, .2]])(170), 200);
62 assert
.strictEqual(invert([[0, 100, .1], [100, Infinity
, .2]])(112), 127.5);
63 assert
.strictEqual(invert([[6, 90, 0.75], [90, Infinity
, 0.12]])(27), 90);
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
)));