Могу ли я использовать объекты поверх оператора Switch? - PullRequest
1 голос
/ 17 марта 2020

Я хочу знать, есть ли альтернативный способ сделать это заявление о переключении более эффективным, возможно, с меньшим количеством кода?

Я слышал об объектах лучше и чище, и нет необходимости использовать разрыв больше. Как я могу использовать это правильно?

Спасибо.

код здесь - https://jsfiddle.net/lmanhaes/cq1g5dyt/4/

$.each(response.weather, function(index) { //retrieve data
      let icon;
      switch (response.weather[index].currentConditions) { //switch case for icons
        case "Cloud":
          icon = '<img src="./weather_icons/cloud.png" alt="cloud" width="22px"/>';
          break;
        case "Hail":
          icon = '<img src="./weather_icons/hail.png" alt="hail" width="22px"/>';
          break;
        case "Heavy Cloud":
          icon = '<img src="./weather_icons/heavy cloud.png" alt="heavy-clouds" width="22px"/>';
          break;
        case "Heavy Rain":
          icon = '<img src="./weather_icons/heavy rain.png" alt="heavy-rain" width="22px"/>';
          break;
        case "Rain":
          icon = '<img src="./weather_icons/rain.png" alt="rain" width="22px"/>';
          break;
        case "Sleet":
          icon = '<img src="./weather_icons/sleet.png" alt="sleet" width="22px"/>';
          break;
        case "Snow":
          icon = '<img src="./weather_icons/snow.png" alt="snow" width="22px"/>';
          break;
        case "Sun":
          icon = '<img src="./weather_icons/sun.png" alt="sun" width="22px"/>';
          break;
        case "Sun and Clouds":
          icon = '<img src="./weather_icons/sun and cloud.png" alt="sun-clouds" width="22px"/>';
          break
        case "Thunderstorm":
          icon = '<img src="./weather_icons/thunderstorm.png" alt="thunderstorm" width="22px"/>';
          break;
      }

Ответы [ 3 ]

0 голосов
/ 17 марта 2020

С каждым погодным условием связаны три уникальные строки: строка, возвращаемая API, имя файла изображения и изображение alt. Вы можете сделать это кратко, используя объект, проиндексированный строкой ответа API, где каждое значение является либо другим объектом, либо массивом:

const weatherStrings = {
  Cloud: ['cloud', 'cloud',
  Hail: ['hail', 'hail'],
  'Heavy Cloud': ['heavy cloud', 'heavy-clouds'],
  // ...
}

// ...

success: function(response) {
  for (const item of response.weather) {
    const [filename, alt] = weatherStrings[item.currentConditions];
    const icon = `<img src="./weather_icons/${filename}.png" alt="${alt}" width="22px">`;
    // ...
  }

Если возможно, вы можете сделать вещи короче и согласованнее, изменив свой бэкэнд на то же имя файла, что и строка currentConditions - например, измените имя файла cloud.png на Cloud.png, а heavy rain.png на Heavy Rain.png. Тогда значение для каждой строки погоды должно быть только строкой alt:

const altsByCurrentConditions = {
  Cloud: 'cloud',
  Hail: 'hail',
  'Heavy Cloud': 'heavy-clouds',
  // ...
}

// ...

success: function(response) {
  for (const item of response.weather) {
    const alt = altsByCurrentConditions[item.currentConditions];
    const icon = `<img src="./weather_icons/${item.currentConditions}.png" alt="${alt}" width="22px">`;
    // ...
  }
0 голосов
/ 17 марта 2020

Я думаю, что это будет лучшим решением для вас

$.each(response.weather, function (index) { //retrieve data
    let icon;
    let currentCondition = response.weather[index].currentConditions.toLowerCase();
    icon = '<img src="./weather_icons/${currentCondition}.png" 
    alt="${currentCondition}" width="22px"/>'; 
}
0 голосов
/ 17 марта 2020

Конечно. Вы можете создать словарь типов погоды.

/** @typedef {{file: string, label: string}} WeatherEntry */
/** @typedef {[key: string]: WeatherEntry} WeatherMap */

/** @type {WeatherMap} */
const weather = {
    "Cloud": {
        "file": "cloud.png",
        "label": "cloud"
    },
    // ...
};

Затем используйте это:

const entry = weather[response.weather[index].currentConditions];
let icon = `<img src="./weather_icons/${entry.file}" alt="${entry.label}" width="22px" />`;
...