Typescript 嵌套开关替代品

问题描述 投票:0回答:1

我有 3 个不同变量的各种组合的各种输出。我能想到的最好的解决方案是嵌套 switch 语句。我只是想知道我是否应该使用更高效/优雅的解决方案?下面是我的意思的一个例子:

function getPaintDefectSeverity(manufacturer: string, model: string, color: string) : String {
  switch(manufacturer){
    case 'FORD': case 'BMW':
      switch(model){
        case 'puma': case 'ranger': case 'escape': case 'x3': case 'x7':
          switch(color){
            case 'red': case 'yellow': 
               return 'full paint defect'
            default: 
               return 'no paint defect'
          }
       default
         return 'no paint defect'
       }
    case 'RENAULT': case 'SEAT': 
       switch(model){
         case 'clio': case 'ibiza': 
            return 'full paint defect'
         case 'megane':
            return 'partial paint defect'
         default: 
            return 'no paint defect'
        }
    case 'AUDI':
         switch(color){
           case 'blue': 
              return 'full paint defect'
           default: 
              return 'no paint defect' 
          }
    default
      return 'no paint defect'
    }

显然这只是一个示例,但我的问题是,有这么多嵌套的 switch 语句一定不好吗?对此的任何建议/指导将不胜感激。

谢谢。

javascript typescript switch-statement
1个回答
0
投票

如果有油漆缺陷的东西相对较少,并且其他一切都很好,则可以使用一两个查找表。像这样的东西:

const paintDefectsByModel = {
  'RENAULT.clio': 'full',
  'RENAULT.megane': 'partial'
  // ...
};

const paintDefectsByModelAndColor = {
  'FORD.ranger.red': 'full',
  'FORD.ranger.yellow': 'full',
  // ...
};

function getPaintDefectSeverity(manufacturer: string, model: string, color: string) : string {
  const modelKey = `${manufacturer}.${model}`;
  let paintDefect = paintDefectsByModel[modelKey];
  if (paintDefect !== undefined) {
    return `${paintDefect} paint defect`;
  }

  const modelColorKey = `${manufacturer}.${model}.${color}`;
  paintDefect = paintDefectsByModelAndColor[modelColorKey];
  if (paintDefect !== undefined) {
    return `${paintDefect} paint defect`;
  }

  return 'no paint defect';
}
© www.soinside.com 2019 - 2024. All rights reserved.