Skip to content

Instantly share code, notes, and snippets.

@bossiernesto
Created February 17, 2020 18:27
Show Gist options
  • Select an option

  • Save bossiernesto/640e5dbc9b8bc870ba7a61ec7d430dce to your computer and use it in GitHub Desktop.

Select an option

Save bossiernesto/640e5dbc9b8bc870ba7a61ec7d430dce to your computer and use it in GitHub Desktop.
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
let numToWords = n => {
let onesGroup = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let tensGroup = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let thousandGroup = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : onesGroup[huns] + ' hundred ',
num(ones) === 0 ? tensGroup[tens] : tensGroup[tens] && tensGroup[tens] + '-' || '',
onesGroup[tens+ones] || onesGroup[ones]
].join('');
};
let thousand = (group,i) => group === '' ? group : `${group} ${thousandGroup[i]}`;
if (typeof n === 'number')
return numToWords(String(n));
else if (n === '0')
return 'zero';
else
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(!isEmpty)
.reverse()
.join(' ');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment