Last active
October 18, 2022 00:11
-
-
Save trueharuu/83a368d68c165b361e193bd6526dcb0e to your computer and use it in GitHub Desktop.
num to word
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
function arr(x: any) { | |
return Array.from(x); | |
} | |
function num(x: any) { | |
return Number(x) || 0; | |
} | |
function str(x: any) { | |
return String(x); | |
} | |
function isEmpty(xs: any) { | |
return xs.length === 0; | |
} | |
function take(n: any) { | |
return (xs: any) => xs.slice(0, n); | |
} | |
function drop(n: any) { | |
return (xs: any) => xs.slice(n); | |
} | |
function reverse(xs: any) { | |
return xs.slice(0).reverse(); | |
} | |
function comp(f: any) { | |
return function(g: any) { | |
return function(x: any) { | |
return f(g(x)); | |
}; | |
}; | |
} | |
function not(x: any) { | |
return !x; | |
} | |
function chunk(n: any) { | |
return (xs: any): any => | |
isEmpty(xs) ? [] : [take(n)(xs), ...chunk(n)(drop(n)(xs))]; | |
} | |
function numToWords(n: any): any { | |
let a = [ | |
'', | |
'one', | |
'two', | |
'three', | |
'four', | |
'five', | |
'six', | |
'seven', | |
'eight', | |
'nine', | |
'ten', | |
'eleven', | |
'twelve', | |
'thirteen', | |
'fourteen', | |
'fifteen', | |
'sixteen', | |
'seventeen', | |
'eighteen', | |
'nineteen' | |
]; | |
let b = [ | |
'', | |
'', | |
'twenty', | |
'thirty', | |
'forty', | |
'fifty', | |
'sixty', | |
'seventy', | |
'eighty', | |
'ninety' | |
]; | |
let g = [ | |
'', | |
'thousand', | |
'million', | |
'billion', | |
'trillion', | |
'quadrillion', | |
'quintillion', | |
'sextillion', | |
'septillion', | |
'octillion', | |
'nonillion' | |
]; | |
function makeGroup([ones, tens, huns]: any[]) { | |
return [ | |
num(huns) === 0 ? '' : a[huns] + ' hundred ', | |
num(ones) === 0 ? b[tens] : (b[tens] && b[tens] + '-') || '', | |
a[tens + ones] || a[ones] | |
].join(''); | |
} | |
function thousand(group: any, i: any) { | |
return group === '' ? group : `${group} ${g[i]}`; | |
} | |
if (typeof n === 'number') return numToWords(String(n)); | |
else if (n === '0') return 'zero'; | |
else | |
return comp(chunk(3))(reverse)(arr(n)) // what the fuck? | |
.map(makeGroup) | |
.map(thousand) | |
.filter(comp(not)(isEmpty)) | |
.reverse() | |
.join(', '); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment