Translate your digits to English [0–999]

The Problem

Write a function that accepts a positive integer between 0 and 999 inclusive and returns a string representation of that integer written in English.

Understand the Problem

We need an output that looks like this:OutputnumToEng(0) ➞ "zero"

numToEng(18) ➞ "eighteen"

numToEng(126) ➞ "one hundred twenty six"

numToEng(909) ➞ "nine hundred nine"
Notes# There are no hyphens used (e.g. “thirty five” not “thirty-five”).
#The word “and” is not used (e.g. “one hundred one” not “one hundred and one”).

Solution

const lessThanTwenty = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
'eleven',
'twelve',
'thirteen',
'fourteen',
'fifteen',
'sixteen',
'seventeen',
'eighteen',
'nineteen',
];
const tenthsLessThanHundred = [
'zero',
'ten',
'twenty',
'thirty',
'forty',
'fifty',
'sixty',
'seventy',
'eighty',
'ninety',
];
const numToEng = (number, words = []) => {
if (number === 0) return words.length ? words.join(' ') : 'zero';
if (number < 20) {
words.push(lessThanTwenty[number]);
return numToEng(0, words);
} else if (number < 100) {
words.push(tenthsLessThanHundred[Math.floor(number / 10)]);
return numToEng(number % 10, words);
} else if (number < 1000) {
words.push(numToEng(Math.floor(number / 100)) + ' hundred');
return numToEng(number % 100, words);
}
};

Output / Testing

It's your turn to test it, use the magic shortcut of copy/paste to your terminal, I am positive it works a 100%.Happy coding.

Software engineer | Full Stack Developer | Programmer | Designer & Entrepreneur