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;
}
Use array...
function dayNumberToString(dayNumber) {
return ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][dayNumber % 7]
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With