TransWikia.com

Don't you think this is ugly? How do I fix switch ugly JS statement

Stack Overflow Asked by hellofanengineer on December 3, 2021

This is so ugly and how do I organize this switch statement?

function renderDataTypeIcon(dataType: string) {
  let iconName; 
  switch (dataType) {
    case "STRING": //TO-DO => ENUM
      iconName = "text";
      break;
    case "NUMBER":
      iconName = "number_input";
      break; 
    case "ARRAY":
      iconName = "standard_objects";
      break; 
    case "DATE":
      iconName = "dayview";
      break; 
    case "OBJECT":
      iconName = "standard_objects";
      break; 
    case "INTEGER":
      iconName = "number_input";
      break;
    case "BOOLEAN":
      iconName = "radio_button";
      break;
    default:
      iconName = "warning"
  }

3 Answers

You can eliminate the temporary variable iconName and all the break statements if you just return the matched string.

function renderDataTypeIcon(dataType: string) {
  switch (dataType) {
    case "STRING": return "text";
    case "NUMBER": return "number_input";
    case "ARRAY": return "standard_objects"; 
    case "DATE": return "dayview";
    case "OBJECT": return "standard_objects";
    case "INTEGER": return "number_input";
    case "BOOLEAN": return "radio_button";
    default: return "warning";
  }
}

Answered by dwmorrin on December 3, 2021

It may be cleaner just to use an object to map the datatypes to icons:

const DATATYPE_TO_ICON: {[key: string]: string} = {
    "STRING":  "text",
    "NUMBER": "number_input",
    "ARRAY": "standard_objects",
    "DATE": "dayview",
    "OBJECT": "standard_objects",
    "INTEGER": "number_input",
    "BOOLEAN": "radio_button",
}

function renderDataTypeIcon(dataType: string) {
    return DATATYPE_TO_ICON[dataType] || "warning";
}

Answered by Spencer Bard on December 3, 2021

Use an object

const dataTypeIcons: { [key: string]: string } = {
  STRING: 'text',
  NUMBER: 'number_input',
  etc
}

and use

const icon = dataTypeIcons[dataType] || 'warning';

Answered by Adrian Brand on December 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP