Debian Codegraph @

addons/point_of_sale/static/src/app/utils/numbers.js

raw
1 import { roundPrecision } from "@web/core/utils/numbers";
2 import { Base } from "@point_of_sale/app/models/related_models";
3
4 export const LT = -1;
5 export const EQ = 0;
6 export const GT = 1;
7
8 export function comp(a, b, { precision = 1, method = "HALF-UP" } = {}) {
9 a = roundPrecision(a, precision, method);
10 b = roundPrecision(b, precision, method);
11 const d = a - b;
12 if (d === 0 || roundPrecision(d, precision, method) === 0) {
13 return EQ;
14 }
15 return d < 0 ? LT : GT;
16 }
17
18 function invertMethod(method) {
19 return method === "UP"
20 ? "DOWN"
21 : method === "DOWN"
22 ? "UP"
23 : method === "HALF-UP"
24 ? "HALF-DOWN"
25 : method === "HALF-DOWN"
26 ? "HALF-UP"
27 : method;
28 }
29
30 export class AbstractNumbers extends Base {
31 get precision() {
32 return Math.pow(10, -2);
33 }
34
35 get method() {
36 return "HALF-UP";
37 }
38
39 comp(a, b) {
40 return comp(a, b, {
41 precision: this.precision,
42 method: this.method,
43 });
44 }
45
46 isZero(a) {
47 return this.comp(a, 0) === EQ;
48 }
49
50 isPositive(a) {
51 return this.comp(a, 0) === GT;
52 }
53
54 isNegative(a) {
55 return this.comp(a, 0) === LT;
56 }
57
58 equal(a, b) {
59 return this.comp(a, b) === EQ;
60 }
61
62 /**
63 * Symmetric rounding.
64 * ```
65 * round(1.23, { precision: 0.1, method: "UP" }) // 1.3
66 * round(-1.23, { precision: 0.1, method: "UP" }) // -1.3
67 * ```
68 */
69 round(a) {
70 return roundPrecision(a, this.precision, this.method);
71 }
72
73 asymmetricRound(a) {
74 return roundPrecision(
75 a,
76 this.precision,
77 // If negative, invert the rounding method
78 this.isNegative(a) ? invertMethod(this.method) : this.method
79 );
80 }
81 }