given a number (n) return the text for hoe it is spoken. e.g.:
10 => "ten"
99 => "ninety nine"
-1 => "negative one"
231 => "two hundred and thirty one"
I will make the smallest number -999 and the largest 999 for simplicity. you can asume all numbers are valid intagers, but check the range. If a number is out of range return "unsupported number";
function Generrate (n)
{
var out = "";
var str_arrOfDigits = n.toString().split("");
if (str_arrOfDigits[0] == "-")
{
out += "negative ";
str_arrOfDigits.splice(0,1);
}
switch (str_arrOfDigits.length) {
case 1:
out += Digits(str_arrOfDigits[0]);
break;
case 2:
out += getDoubleDigit(str_arrOfDigits);
break;
case 3:
out += getTrippleDigit(str_arrOfDigits)
break;
default:
return "unsupported number";
break;
}
return out;
};
function Digits(n) {
return ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"][n];
};
function tens(n) {
return ["zero", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"][n];
};
function getDoubleDigit (arr)
{
var out = "";
if (arr[0] == "1") {
out = Digits(arr.join().replace("," ,""));
}
else {
if (arr[0] != "0")
out = tens(arr[0]) + (arr[1] != "0"? " " + Digits(arr[1]): "");
else
out = Digits(arr[1]);
}
return out;
}
function getTrippleDigit (arr)
{
var firstDigit = Digits(arr[0]);
var doubleDigits = getDoubleDigit(arr.splice(1));
return (firstDigit != "zero"? firstDigit + " hundred" : "") + (firstDigit != "zero" && doubleDigits != "zero"? " and " + doubleDigits : (doubleDigits != "zero"? doubleDigits : ""));
}
describe("Solution", function(){
it("Tests", function(){
Test.assertEquals(Generrate(1), "one", "obviousesly includes 1");
Test.assertEquals(Generrate(0), "zero", "should work with 0");
Test.assertEquals(Generrate(1000), "unsupported number", "out of range");
Test.assertEquals(Generrate(-10), "negative ten", "should work with negative numbers");
Test.assertEquals(Generrate(320), "three hundred and twenty", "should work with triple digits");
});
});