amirfl amirfl - 4 months ago 8
Javascript Question

Convert hours, minutes, seconds - cleaner code

I created this function in javascript that converts between different time units.

For example, calling

convertTimes(90,{symbol:"min"},{symbol:"hour"})
returns 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 }
}
}


Could you suggest a way of refactoring/cleaning this code so it doens't nest so many if-else calls?

Answer
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]
Comments