|
1
|
import { describe, expect, it } from "vitest" |
|
2
|
import { divideDecimal, multiplyDecimal } from "../number-helper" |
|
3
|
|
|
4
|
describe("multiplyDecimal", () => { |
|
5
|
it("avoids the representation error of the native operator", () => { |
|
6
|
expect(3 * 0.1).not.toBe(0.3) // sanity check on the premise |
|
7
|
expect(multiplyDecimal(3, 0.1)).toBe(0.3) |
|
8
|
expect(multiplyDecimal(3, 1.1)).toBe(3.3) |
|
9
|
expect(multiplyDecimal(1.005, 100)).toBe(100.5) |
|
10
|
}) |
|
11
|
|
|
12
|
it("multiplies common fractions exactly", () => { |
|
13
|
expect(multiplyDecimal(4, 0.25)).toBe(1) |
|
14
|
expect(multiplyDecimal(3, 0.5)).toBe(1.5) |
|
15
|
expect(multiplyDecimal(8, 0.125)).toBe(1) |
|
16
|
}) |
|
17
|
|
|
18
|
it("preserves operands smaller than a fixed rounding cap would keep", () => { |
|
19
|
expect(multiplyDecimal(3, 1e-7)).toBe(3e-7) |
|
20
|
expect(multiplyDecimal(0.00001, 0.00001)).toBe(1e-10) |
|
21
|
}) |
|
22
|
|
|
23
|
it("is a no-op for a factor of one", () => { |
|
24
|
expect(multiplyDecimal(42, 1)).toBe(42) |
|
25
|
}) |
|
26
|
|
|
27
|
it("handles zero and negative operands", () => { |
|
28
|
expect(multiplyDecimal(0, 0.25)).toBe(0) |
|
29
|
expect(multiplyDecimal(-3, 0.1)).toBe(-0.3) |
|
30
|
}) |
|
31
|
}) |
|
32
|
|
|
33
|
describe("divideDecimal", () => { |
|
34
|
it("avoids losing a whole unit when the caller floors the result", () => { |
|
35
|
expect(Math.floor(7 / 0.07)).toBe(99) // sanity check on the premise |
|
36
|
expect(Math.floor(divideDecimal(7, 0.07))).toBe(100) |
|
37
|
expect(Math.floor(divideDecimal(14, 0.28))).toBe(50) |
|
38
|
expect(Math.floor(divideDecimal(0.3, 0.1))).toBe(3) |
|
39
|
}) |
|
40
|
|
|
41
|
it("divides by common fractions exactly", () => { |
|
42
|
expect(divideDecimal(98.25, 0.25)).toBe(393) |
|
43
|
expect(divideDecimal(1, 0.125)).toBe(8) |
|
44
|
}) |
|
45
|
|
|
46
|
it("leaves genuinely fractional results intact", () => { |
|
47
|
expect(Math.floor(divideDecimal(10, 3))).toBe(3) |
|
48
|
expect(Math.floor(divideDecimal(7, 2))).toBe(3) |
|
49
|
}) |
|
50
|
|
|
51
|
it("is a no-op for a divisor of one", () => { |
|
52
|
expect(divideDecimal(42, 1)).toBe(42) |
|
53
|
}) |
|
54
|
|
|
55
|
it("propagates division by zero as the native operator does", () => { |
|
56
|
expect(divideDecimal(1, 0)).toBe(Infinity) |
|
57
|
}) |
|
58
|
}) |