JSFiddle - React, Tailwind, and code Playground

by dpnminh

JavaScript

var numberToWords = function(num) {
    var markUps = {
        3: " Hundred",
        4: " Thousand",
        6: " Hundred",
        7: " Million",
        9: " Hundred",
        10: " Billion"
    };
    
    if (num <= 99) return getBelowHundredWord(num);
    
    var x = 2, modBy = 10 ** x, minus = 2, remainder = num % modBy, syntax = "", words = "", stop = false, needSyntaxAnyway = false;
    
    while (!stop){
        stop = remainder === num;
        
        var divideBy = 10 ** (x - minus), 
            digit = Math.floor(remainder / divideBy),
            word = getBelowHundredWord(digit);
        
        if (word === "Zero"){
            word = "";
            
            if (needSyntaxAnyway){
                word = syntax.trim() + " ";
            }
        }
        else{
            word = word + syntax + " ";
        }
        
        words = word + words;
        
        x++;
        syntax = markUps[x] || "";
        
        if (x === 7 || x === 4){
            x++;
            minus = 2;
            needSyntaxAnyway = true;
        }
        else{
            minus = 1;
            needSyntaxAnyway = false;
        }
        
        modBy = 10 ** x;
        remainder = num % modBy;
    }
    
    words = words.replace('Million Thousand ', 'Million ');
    words = words.replace('Billion Million ', 'Billion ');
    
    return words.trim();
};

function getBelowHundredWord(num){
     var belowTwenty = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
                        "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
    var specialDigits = {
        2: "Twen",
        3: "Thir",
        4: "For",
        5: 'Fif',
        8: 'Eigh'
    }
    
    if (belowTwenty[num]) return belowTwenty[num];
    
    //Else >=20
    var digit = Math.floor(num / 10), remainder = num % 10;
    var str = (specialDigits[digit] ? specialDigits[digit] :...