I have a challenge, which is to create a JavaScript function that turns a given number into the string representation. For example:
console.log(inToEnglish(15))
should print fifteen
console.log(inToEnglish(101))
should print one hundred one
and so on...
This challenge covers Non-Negative, greater than zero Integer numbers.
I have accomplished this objective with the following code:
var b4Twenty = ["one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"
];
var b4Hundred = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"
];
function intToEnglish(n) {
return translator(n).trim();
}
function translator(n) {
if( n == 0)
return "";
else if (n <= 19)
return b4Twenty[n - 1] + " ";
else if (n <= 99)
return b4Hundred[Math.floor(n / 10 - 2)] + " " + translator(n % 10);
else if (n <= 199)
return "one hundred " + translator(n % 100);
else if (n <= 999)
return translator(Math.floor(n / 100)) + "hundred " + translator(n % 100);
else if (n <= 1999)
return "one thousand " + translator(n % 1000);
else if (n <= 999999)
return translator(Math.floor(n / 1000)) + "thousand " + translator(n % 1000);
else if (n <= 1999999)
return "one million " + translator(n % 1000000);
else if (n <= 999999999)
return translator(Math.floor(n / 1000000)) + "million " + translator(n % 1000000);
else if (n <= 1999999999)
return "one billion " + translator(n % 1000000000);
else if (n <= 999999999999)
return translator(Math.floor(n / 1000000000)) + "billion " + translator(n % 1000000000);
else if (n <= 1999999999999)
return "one trillion " + translator(n % 1000000000000);
else if(n <= 999999999999999)
return translator(Math.floor(n / 1000000000000)) + "trillion " + translator(n % 1000000000000);
else if (n <= 1999999999999999)
return "one quadrillion " + translator(n % 1000000000);
else
return translator(Math.floor(n / 1000000000000000)) + "quadrillion " + translator(n % 1000000000000000);
}
This is my recursive function to achieve the given goal. It works, and it takes 65ms to complete the battery of 50 tests.
However, I have some concerns regarding its performance:
- Given that recursive functions are usually slower than iterative ones, is there a way to make this iterative?
- Should I use a
switch
case, or is myif
statement OK? - I keep using
Math.floor
to round the numbers and find the indexes. Perhaps there is a better solution out there without using this technique? - I have to wrap the translator function (who does all the work) into another function because I need to
trim
the final result of extra spaces. Is there a way I can avoid this?
I am open to suggestions on how to improve this. Thanks!
before
and notb4
. Also I think that before isn't the best choice for what you want to express. Below is a better fit. \$\endgroup\$