-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
in_words.ts
121 lines (119 loc) · 2.37 KB
/
in_words.ts
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const digits = [
"",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
];
const teens = [
"",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
];
const tens = [
"",
"ten",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety",
];
const tenPowers = {
int: [
"{ones}",
"{tens}",
"{ones} hundred and",
"{ones} thousand,",
"{tens}",
"{ones} hundred and",
"{ones} million,",
"{tens}",
"{ones} hundred and",
"{ones} billion,",
"{tens}",
"{ones} hundred and",
"{ones} trillion,",
"{tens}",
"{ones} hundred and",
"{ones} thousand,",
"{tens}",
],
in: [
"{ones}",
"{tens}",
"{ones} hundred and",
"{ones} thousand,",
"{tens}",
"{ones} lakh,",
"{tens}",
"{ones} crore,",
"{tens}",
"{ones} hundred and",
"{ones} thousand,",
"{tens}",
"{ones} lakh,",
"{tens}",
"{ones} crore,",
"{tens}",
],
};
/**
* Get the right template for the digit.
* @param {number} i - Number's place to parse.
* @param {boolean} indian - Whether to use Indian system.
* @returns
*/
function getTenPower(i: number, indian = false) {
const arr = indian ? tenPowers.in : tenPowers.int;
i = i % arr.length;
return arr[i];
}
/**
* Parse a number into an english word string.
* @param {number} n - The number to parse.
* @param {boolean} indian - Whether to use Indian system.
* @returns {string} The number in words.
*/
export default function (n: number, indian = false): string {
if (n === 0) return "zero";
const digitNumbers: number[] = n.toString().split("").map((x) => Number(x))
.reverse();
const digitStrings: string[] = [];
for (let i = 0; i < digitNumbers.length; ++i) {
if (getTenPower(i + 1, indian)?.startsWith("{tens}")) {
if (digitNumbers[i + 1] === 1) {
digitStrings.push(
`${teens[digitNumbers[i]]} ${
getTenPower(i, indian).replace(/\{ones\}\s?/, "")
}`,
);
++i;
continue;
}
}
digitStrings.push(
getTenPower(i, indian).replace(
"{ones}",
digits[digitNumbers[i]],
).replace("{tens}", tens[digitNumbers[i]]),
);
console.log((i - digitNumbers.length ))
}
return digitStrings.reverse().join(" ");
};