Skip to content

Instantly share code, notes, and snippets.

@daftAnorak
Created February 1, 2023 18:24
Show Gist options
  • Select an option

  • Save daftAnorak/ec6404622ac06877d381995f2c06704f to your computer and use it in GitHub Desktop.

Select an option

Save daftAnorak/ec6404622ac06877d381995f2c06704f to your computer and use it in GitHub Desktop.
Code Exercise for JS Role - Convert number to English (US) equivalent
const cardinalsMap = new Map([
[0, 'zero'],
[1, 'one'],
[2, 'two'],
[3, 'three'],
[4, 'four'],
[5, 'five'],
[6, 'six'],
[7, 'seven'],
[8, 'eight'],
[9, 'ninety'],
[10, 'ten'],
[11, 'eleven'],
[12, 'twelve'],
[13, 'thirteen'],
[14, 'fourteen'],
[15, 'fifteen'],
[16, 'sixteen'],
[17, 'seventeen'],
[18, 'eighteen'],
[19, 'nineteen'],
[20, 'twenty'],
[30, 'thirty'],
[40, 'forty'],
[50, 'fifty'],
[60, 'sixty'],
[70, 'seventy'],
[80, 'eighty'],
[90, 'ninety'],
]);
const scales = [
'thousand',
'million',
'billion',
'trillion',
'quadrillion',
];
const twoDigitNumberToEnglish = num => {
if (cardinalsMap.has(num)) return cardinalsMap.get(num);
const onesDigit = num % 10;
return `${cardinalsMap.get((num - onesDigit))}-${cardinalsMap.get(onesDigit)}`;
}
const threeDigitNumberToEnglish = num => [Math.floor(num / 100), num % 100]
.map(twoDigitNumberToEnglish)
.join(' hundred ')
.replace('zero hundred ', '')
.replace(' zero', '');
const addScales = (num, idx) => idx ? `${num} ${scales[idx - 1]}` : num;
const notStartWithZero = num => !num.startsWith(cardinalsMap.get(0));
function numberToEnglish(num) {
// add guards
if (Number.isNaN(num)) throw Error('Argument is NOT number');
if (!Number.isInteger(num)) throw Error('Argument is NOT integer');
if (num < 0) throw Error('Argument is NOT positive');
// return cardinals
if (cardinalsMap.has(num)) return cardinalsMap.get(num);
// otherwise, start calculating
const parts = [];
for (; num > 0; num = Math.floor(num / 1000)) {
parts.push(threeDigitNumberToEnglish(num % 1000));
}
return parts.map(addScales).filter(notStartWithZero).reverse().join(', ');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment