Guest User

Untitled

a guest
Jul 18th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. /**
  2. * @param {number} num
  3. * @return {string}
  4. */
  5. const thousand = 1000;
  6. const million = thousand * thousand;
  7. const billion = million * thousand;
  8. const trillion = billion * thousand;
  9. const quadrillion = trillion * thousand
  10. const quintillion = quadrillion * thousand;
  11.  
  12. const units = [undefined, "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
  13. const teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
  14. const tens = [undefined, "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
  15.  
  16. function subHundred(num){
  17. const trimmed = num % 100
  18. const unit = trimmed % 10;
  19. const ten = Math.floor(trimmed / 10);
  20.  
  21. if(ten >= 2){
  22. return [tens[ten], units[unit]]
  23. .filter(part => part)
  24. .join(' ');
  25. }
  26. if(ten >= 1){
  27. return teens[unit];
  28. }
  29. return units[unit];
  30. }
  31.  
  32. function subThousand(num){
  33. const trimmed = num % 1000;
  34. const parts = [trimmed >= 100 && `${units[Math.floor(trimmed / 100)]} Hundred`, subHundred(trimmed)];
  35. return parts.filter(part => part).join(' ') || undefined;
  36. }
  37.  
  38. function getThousandPower(min, word) {
  39. return function(num){
  40. const numOfMins = subThousand(Math.floor((num % (min * thousand)) / min ));
  41. return numOfMins && `${numOfMins} ${word}`;
  42. }
  43. }
  44. var numberToWords = function(num) {
  45. return [
  46. getThousandPower(quadrillion, "Quadrillion"),
  47. getThousandPower(trillion, "Trillion"),
  48. getThousandPower(billion, "Billion"),
  49. getThousandPower(million, "Million"),
  50. getThousandPower(thousand, "Thousand"),
  51. subThousand
  52. ].map(proc => proc(num))
  53. .filter(part => part)
  54. .join(" ") || "Zero";
  55. };
  56.  
  57. [000, 12345, 1234567, 1234567891].forEach(num => {
  58. console.log(numberToWords(num));
  59. });
Add Comment
Please, Sign In to add comment