Last active
September 8, 2023 13:57
-
-
Save codeaholicguy/19f851d2928f3b8b77d5892af1765840 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Notions = { | |
1: 'Thousand', | |
2: 'Million', | |
3: 'Billion', | |
} | |
const UnderTwenty = { | |
0: '', | |
1: 'One', | |
2: 'Two', | |
3: 'Three', | |
4: 'Four', | |
5: 'Five', | |
6: 'Six', | |
7: 'Seven', | |
8: 'Eight', | |
9: 'Nine', | |
10: 'Ten', | |
11: 'Eleven', | |
12: 'Twelve', | |
13: 'Thirteen', | |
14: 'Fourteen', | |
15: 'Fifteen', | |
16: 'Sixteen', | |
17: 'Seventeen', | |
18: 'Eighteen', | |
19: 'Nineteen', | |
20: 'Twenty', | |
} | |
const Named = { | |
...UnderTwenty, | |
0: 'Zero', | |
} | |
const Dozen = { | |
2: 'Twenty', | |
3: 'Thirty', | |
4: 'Forty', | |
5: 'Fifty', | |
6: 'Sixty', | |
7: 'Seventy', | |
8: 'Eighty', | |
9: 'Ninety', | |
} | |
const chunklify = (num) => { | |
const arr = num.toString() | |
const chunks = [] | |
let count = 1 | |
let tmp = [] | |
for (let i = arr.length - 1; i >=0; i--) { | |
if (count == 3) { | |
tmp.push(arr[i]) | |
chunks.push(tmp.reverse()) | |
count = 1 | |
tmp = [] | |
} else { | |
if (arr[i]) { | |
count++; | |
tmp.push(arr[i]) | |
} | |
if (i == 0) { | |
chunks.push(tmp.reverse()) | |
} | |
} | |
} | |
return chunks | |
} | |
const trans = (num) => { | |
if (num <= 20) { | |
return Named[num] | |
} | |
const chunks = chunklify(num); | |
const texts = chunks.map((chunk) => { | |
let text = '' | |
let value = 0 | |
if (chunk.length == 3) { | |
if (UnderTwenty[chunk[0]]) { | |
text = `${UnderTwenty[chunk[0]]} Hundred` | |
} | |
value = parseInt(`${chunk[1]}${chunk[2]}`) | |
if (value <= 20) { | |
if (text) { | |
if (UnderTwenty[value]) { | |
text = `${text} ${UnderTwenty[value]}` | |
} | |
} else { | |
text = `${UnderTwenty[value]}` | |
} | |
} else { | |
text = `${text} ${Dozen[chunk[1]]} ${UnderTwenty[chunk[2]]}` | |
} | |
} else if (chunk.length == 2) { | |
value = parseInt(`${chunk[0]}${chunk[1]}`) | |
if (value <= 20) { | |
text = `${UnderTwenty[value]}` | |
} else { | |
text = `${Dozen[chunk[0]]} ${UnderTwenty[chunk[1]]}` | |
} | |
} else { | |
value = parseInt(`${chunk[0]}`) | |
text = `${UnderTwenty[value]}` | |
} | |
return text | |
}) | |
const textsWithNotion = texts.map((text, i) => { | |
if (i > 0) { | |
if (text) { | |
return `${text} ${Notions[i]}` | |
} | |
return `${text}` | |
} | |
return `${text}` | |
}, '') | |
const result = textsWithNotion.reverse().join(' ') | |
return result.trim().replace(/\s+/g, ' ') | |
} | |
console.log(trans(1000000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment