Reputation: 15
I am developing a very simple weather app in Angular and I wanted to ask you if you think there are better ways to choose a certain image based on the "type" of weather codition.
enum WeatherCodition {
Thunderstorm = 0,
Drizzle,
Rain,
Snow,
Clear,
Clouds
}
export class Weather {
getIcon(condition: WeatherCodition): string {
var iconPath = "";
switch(condition){
case WeatherCodition.Thunderstorm:
iconPath = "thunderstorm.png";
break;
case WeatherCodition.Clouds:
iconPath = "clouds.png";
break;
case WeatherCodition.Drizzle:
iconPath = "drizzle.png";
break;
case WeatherCodition.Rain:
iconPath = "rain.png";
break;
case WeatherCodition.Snow:
iconPath = "snow.png";
break;
default:
iconPath = "clear.png"
}
return iconPath;
}
}
Upvotes: 1
Views: 2445
Reputation: 375
Please, consider using interface KeyValue<K, V>
as array. My solution:
export enum WeatherCodition {
Thunderstorm = 0,
Drizzle,
Rain,
Snow,
Clear,
Clouds
}
import { KeyValue } from '@angular/common';
export class Weather {
public keyValueArray: KeyValue<WeatherCodition, string>[] =
[
{ key: WeatherCodition.Thunderstorm, value: "thunderstorm.png" },
{ key: WeatherCodition.Drizzle , value: "drizzle.png"},
{ key: WeatherCodition.Rain, value: "rain.png" },
{ key: WeatherCodition.Snow, value: "snow.png" },
{ key: WeatherCodition.Clear, value: "clear.png" },
{ key: WeatherCodition.Clouds, value: "clouds.png" },
];
getIcon(condition: WeatherCodition): string {
//check if 'condition' exists in array as key
return this.keyValueArray[condition] ?
this.keyValueArray[condition].value :
"clear.png";
}
}
Have a nice day!
Upvotes: 2
Reputation: 3140
Your approach is perfectly fine. You can also create a hashmap for constant time lookup as you are anyway harcoding the urls in your switch statement.
interface WeatherIcons {
Thunderstorm: string;
Clouds: string;
}
const icons: WeatherIcons = {
Thunderstorm: "Thunderstorm.jpg",
Clouds: "Clouds.jpg"
}
function getIcon(condition: WeatherCondition) {
return icons[condition] || "default.jpg";
}
Upvotes: 0
Reputation: 57979
Why not defined an array?
iconPaths:string[]=["thunderstorm.png","clouds.png","drizzle.png","rain.png","snow.png",
"clear.png"]
iconPath=this.iconPaths[condition];
//or
iconPath=(condition && condition<6)?this.iconPaths[condition]:"";
Upvotes: 0
Reputation: 37755
You can create a object and access property based on key
let WeatherCodition = {
thunderstorm:"thunderstorm.png",
clouds:"clouds.png",
drizzle:"drizzle.png",
rain:"rain.png",
snow:"snow.png",
default:"clear.png"
}
function getIcon(condition) {
condition = condition || ""
condition = Object.keys(WeatherCodition).find(c=> c.toLowerCase() === condition.toLowerCase()) || 'default'
return WeatherCodition[condition]
}
console.log(getIcon(''))
console.log(getIcon('Clouds'))
console.log(getIcon())
console.log(getIcon('SnoW'))
Upvotes: 0