-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.js
79 lines (70 loc) · 2.57 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const { oneToTwenty, thousandMultiples } = require("./numberToString");
const persianNumbers = require("./functions/utils");
const formatFragment = require("./functions/formatFragment");
Number.prototype.format = function(n, x) {
var re = "\\d(?=(\\d{" + (x || 3) + "})+" + (n > 0 ? "\\." : "$") + ")";
return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, "g"), "$&,");
};
class Iramount {
constructor(amount) {
if (typeof amount !== "number")
throw new Error(
`param ${amount} type is ${typeof amount}; it should be number`
);
this.amount = amount;
}
digitGrouped(
formatType = "R",
language = "En",
groupDigitBy = 3,
amount = this.amount
) {
if (typeof amount !== "number")
return new Error(
`param ${amount} type is ${typeof amount}; it should be number`
);
if (formatType.toLowerCase() === "r" && language.toLowerCase() === "en")
return amount.format(0, groupDigitBy);
if (formatType.toLowerCase() === "t" && language.toLowerCase() === "en")
return (amount / 10).format(1, groupDigitBy);
if (formatType.toLowerCase() === "r" && language.toLowerCase() === "fa")
return persianNumbers(amount.format(0, groupDigitBy));
if (formatType.toLowerCase() === "t" && language.toLowerCase() === "fa")
return persianNumbers((amount / 10).format(1, groupDigitBy));
return new Error(
`FormatType shuld be R for rial || T for toman. You entered ${formatType} && language sholud be fa || en. You entered ${language}`
);
}
farsiFormat(amount = this.amount) {
const groups = this.digitGrouped(undefined, undefined, 3, amount).split(
","
);
return groups
.map((group, index) => {
let number = parseInt(group);
let farsiRep = "";
if (number !== 0 && index !== 0) farsiRep += " و ";
farsiRep += formatFragment(number);
if (number !== 0)
farsiRep += ` ${thousandMultiples[groups.length - 1 - index]}`;
return farsiRep;
})
.join("")
.trim();
}
farsiFormatRial() {
return this.farsiFormat(this.amount) + " ریال";
}
farsiFormatToman(options = {}) {
const { showRial = false } = options;
if (typeof showRial !== "boolean")
return new Error("Invalid value for showRial");
const tomanFormat =
this.farsiFormat(Math.floor(this.amount / 10)) + " تومان";
const remOfTen = this.amount % 10;
return remOfTen === 0 || showRial === false
? tomanFormat
: tomanFormat + " و " + oneToTwenty[remOfTen] + " ریال";
}
}
module.exports = Iramount;