转换小时,分钟,秒 - 更干净的代码

时间:2016-08-03 21:12:24

标签: javascript refactoring

我在javascript中创建了这个函数,可以在不同的时间单位之间进行转换。
例如,调用convertTimes(90,{symbol:"min"},{symbol:"hour"})返回1.5

function convertTimes(oldTimeValue, oldTimeUnits, newTimeUnits){
  const newTimeUnitSymbol = newTimeUnits.symbol

  if (oldTimeUnits.symbol === newTimeUnitSymbol) { return oldTimeValue }

  if (oldTimeUnits.symbol === "hour") { 
      if (newTimeUnitSymbol === "min") { return oldTimeValue * 60 }
      else if (newTimeUnitSymbol === "sec") { return oldTimeValue * 3600 }

  } else if (oldTimeUnits.symbol === "min") { 
      if (newTimeUnitSymbol === "hour") { return oldTimeValue / 60 }
      else if (newTimeUnitSymbol === "sec") { return oldTimeValue * 60 }

  } else if (oldTimeUnits.symbol === "sec") { 
      if (newTimeUnitSymbol === "hour") { return oldTimeValue / 3600 }
      else if (newTimeUnitSymbol === "min") { return oldTimeValue / 60 }
  }
} 

您能否建议一种重构/清理此代码的方法,以便它不会嵌套这么多if-else调用?

2 个答案:

答案 0 :(得分:1)

var conversions = {
hour: {
    min: 60,
    sec: 3600
},
min: {
    hour: 1/60,
    sec: 60
},
sec:{
    hour: 1/3600,
    min: 1/60
}
}

return oldTimeValue * conversions[oldTimeUnits.symbol][newTimeUnitSymbol]

答案 1 :(得分:1)

如何将符号组合映射到比率?

const CONVERSION = {
  "hour:min":60,
  "hour:sec":3600,
  "min:hour":1/60,
  "min:sec":60,
  "sec:hour":1/3600,
  "sec:min":1/60
}

function convertTimes(oldTimeValue, oldTimeUnits, newTimeUnits){
  // TODO validate symbols
  if (oldTimeUnits.symbol === newTimeUnits.symbol) { return oldTimeValue }
  return oldTimeValue * CONVERSION[oldTimeUnits.symbol+":"+newTimeUnits.symbol];
}