Last active
August 29, 2015 13:57
-
-
Save catdad/9541377 to your computer and use it in GitHub Desktop.
This is a rough draft of code that will type out in words the number that you give it. For example, `say(123)` will return `one hundred twenty three`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var oneDigit = { | |
'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', | |
'6': 'six', '7': 'seven', '8': 'eight', '9': 'nine' | |
}; | |
var teens = { | |
'10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', | |
'14': 'fourteen', '15': 'fifteen', '16': 'sixteen', | |
'17': 'seventeen', '18': 'eighteen', '19': 'nineteen' | |
}; | |
var twoDigit = { | |
'2': 'twenty', '3': 'thirty', '4': 'fourty', '5': 'fifty', | |
'6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety' | |
}; | |
var names = { | |
'1': 'thousand', '2': 'million', '3': 'billion', '4': 'trillion', | |
'5': 'quadrillion', '6': 'sextillion', '7': 'septillion', | |
'8': 'octillion', '9': 'nonillion', '10': 'decillion' | |
}; | |
var processTwoDigit = function(a, b){ | |
var str = ''; | |
if (a === '0'){ | |
//skip, go to next digit | |
str += (b === '0') ? '' : (oneDigit[b]); | |
} | |
else if (a === '1'){ | |
str += teens[( a + '' + b )]; | |
} | |
else{ | |
str += ' ' + twoDigit[a]; | |
str += (b === '0') ? '' : (' ' + oneDigit[b] ); | |
} | |
return str; | |
} | |
var processHundred = function(arr){ | |
var str = ''; | |
str += oneDigit[arr[0]] + ' hundred'; | |
if (arr[1] === '0' || arr[1] === '1'){ | |
//skip, go to next digit | |
str += (arr[2] === '0') ? '' : (' and '); | |
} | |
str += processTwoDigit(arr[1], arr[2]); | |
return str; | |
}; | |
var split = function split(num){ | |
var str = num.toString(); | |
var arr = str.split(''); | |
return arr; | |
}; | |
var splitInThrees = function(arr){ | |
var temp = [], result = []; | |
while(arr.length){ | |
if (temp.length === 3){ | |
result.push(temp.reverse()); | |
temp = []; | |
} | |
temp.push(arr.pop()); | |
} | |
result.push(temp.reverse()); | |
return result.reverse(); | |
}; | |
var say = function say(num){ | |
var arr2d = splitInThrees(split(num)); | |
var res = []; | |
arr2d = arr2d.reverse(); | |
arr2d.forEach(function(arr, i, d2){ | |
var str = ''; | |
switch (arr.length){ | |
case 1: | |
str += oneDigit[arr[0]]; | |
break; | |
case 2: | |
str += processTwoDigit(arr[0], arr[1]); | |
break; | |
case 3: | |
str += processHundred(arr); | |
} | |
str += (i) ? (' ' + names[i]) : ''; | |
res.push(str); | |
}); | |
res = res.reverse(); | |
return res.join(', '); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment