blackdaemon
blackdaemon

Reputation: 755

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;
    }

Upvotes: 2

Views: 230

Answers (4)

user663031
user663031

Reputation:

This is precisely what TypeScript enums are for.

// outside the class
enum Day { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

class Foo {
  private _convertIntToStringDays(days: number[]) {
    return days.map(day => Day[day]);
  }
}

For reference, TS transpiles the enum into the following, allowing bi-directional lookup:

var Day;
(function (Day) {
    Day[Day["sunday"] = 0] = "sunday";
    Day[Day["monday"] = 1] = "monday";
    Day[Day["tuesday"] = 2] = "tuesday";
    Day[Day["wednesday"] = 3] = "wednesday";
    Day[Day["thursday"] = 4] = "thursday";
    Day[Day["friday"] = 5] = "friday";
    Day[Day["saturday"] = 6] = "saturday";
})(Day || (Day = {}));

Upvotes: 1

Thilo
Thilo

Reputation: 262834

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

Upvotes: 4

h0x91B
h0x91B

Reputation: 1256

Use array...

function dayNumberToString(dayNumber) {
    return ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][dayNumber % 7]
}

Upvotes: 4

Jozef Dúc
Jozef Dúc

Reputation: 963

Save name of days in the array and index it with your variable

private _convertIntToStringDays(days: any) {
        let dayArray: any = [];
        let dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
        for (let day in days){
            dayArray.push(dayNames[days[day]]);
        }
        dayArray.shift(dayArray[0]);
        console.log(dayArray);
        return dayArray;
}

Upvotes: 3

Related Questions