UNPKG

3.07 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const ONE = 'หนึ่ง';
4const TWO = 'สอง';
5const THREE_TO_NINE = ['สาม', 'สี่', 'ห้า', 'หก', 'เจ็ด', 'แปด', 'เก้า'];
6const ED = 'เอ็ด';
7const YEE = 'ยี่';
8const LAN = 'ล้าน';
9const EMPTY = '';
10const DIGIT = [EMPTY, 'สิบ', 'ร้อย', 'พัน', 'หมื่น', 'แสน'];
11const ONES = [EMPTY, ED, TWO, ...THREE_TO_NINE];
12const TENS = [EMPTY, ...[EMPTY, YEE, ...THREE_TO_NINE].map(t => t + DIGIT[1])];
13const SUB_HUNDRED = TENS.flatMap(t => ONES.map(o => t + o));
14SUB_HUNDRED[1] = ONE;
15const SUB_TEN = [EMPTY, ONE, TWO, ...THREE_TO_NINE];
16function numberToWords(num) {
17 let output = EMPTY;
18 const length = num.length;
19 for (let i = 0; i < length; i++) {
20 const d = num[i];
21 const di = length - i - 1;
22 const diMod = di % 6;
23 const isSib = diMod === 1;
24 switch (d) {
25 case '0':
26 break;
27 case '1':
28 if (isSib) {
29 output += DIGIT[diMod];
30 }
31 else if (!diMod && i) {
32 output += ED;
33 }
34 else {
35 output += SUB_TEN[Number(d)] + DIGIT[diMod];
36 }
37 break;
38 default:
39 if (isSib && d === '2') {
40 output += YEE + DIGIT[diMod];
41 }
42 else {
43 output += SUB_TEN[Number(d)] + DIGIT[diMod];
44 }
45 break;
46 }
47 if (!diMod && di) {
48 output += LAN;
49 }
50 }
51 return output;
52}
53function bahtText(userInput) {
54 let baht;
55 let bahtStr;
56 let satang;
57 let isNegative = false;
58 let input;
59 if (typeof userInput === 'number') {
60 if (userInput > Number.MAX_SAFE_INTEGER)
61 return false;
62 input = userInput;
63 }
64 else {
65 input = Number(userInput);
66 if (isNaN(input) || input > Number.MAX_SAFE_INTEGER) {
67 return false;
68 }
69 }
70 if (input < 0) {
71 isNegative = true;
72 input = -input;
73 }
74 satang = Number.isInteger(input) ? 0 : (Math.round(input % 1 * 100));
75 baht = Number.isInteger(input) ? input : Math.floor(input);
76 if (satang >= 100) {
77 baht++;
78 satang %= 100;
79 }
80 bahtStr = '' + baht;
81 if (!baht && !satang) {
82 return 'ศูนย์บาทถ้วน';
83 }
84 let output = isNegative ? 'ลบ' : EMPTY;
85 // Baht
86 output += numberToWords(bahtStr);
87 // Satang
88 if (satang) {
89 if (baht)
90 output += 'บาท';
91 // Faster!
92 output += SUB_HUNDRED[satang] + 'สตางค์';
93 // output += SUB_HUNDRED_FUNC(satang) + 'สตางค์'
94 // output += numberToWords(satang.toString()) + 'สตางค์';
95 }
96 else {
97 output += 'บาทถ้วน';
98 }
99 return output;
100}
101exports.default = bahtText;