Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optmise if else Condition javaScript

I have a TypeScript method. It's converting/mapping integer values to string days. How can I improve this code into something more efficient? Any idea?

private _convertIntToStringDays(days: any){
        let dayArray: any = [];
        for (let day in days){
            if (days[day] == 1){
                dayArray.push('monday');
            }
            else if (days[day] == 2){
                dayArray.push('tuesday');
            }
            else if (days[day] == 3){
                dayArray.push('wednesday');
            }
            else if (days[day] == 4){
                dayArray.push('thursday');
            }
            else if (days[day] == 5){
                dayArray.push('friday');
            }
            else if (days[day] == 6){
                dayArray.push('saturday');
            }
            else if (days[day] == 0){
                dayArray.push('sunday');
            }
        }
        dayArray.shift(dayArray[0]);
        console.log(dayArray);
        return dayArray;
    }
like image 279
blackdaemon Avatar asked Aug 13 '26 23:08

blackdaemon


2 Answers

Use array...

function dayNumberToString(dayNumber) {
    return ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][dayNumber % 7]
}
like image 197
h0x91B Avatar answered Aug 16 '26 13:08

h0x91B


Have a lookup table:

const dayNames = [ "Sunday", "Monday", "Tuesday", .... ]
console.log(dayNames[1]) // gives you Monday

[1,0,2].map(x => dayNames[x])  // converts an array of day numbers
like image 45
Thilo Avatar answered Aug 16 '26 14:08

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!