How to minify code structure without using if else statement

1191 views javascript
5

I would like to ask if there is a better way to minify the code below without using if else statement. I have tried using switch case but it does not seem to work:

function (inputValueTime){
if (inputValueTime === 'thirty') {
return 1800000;
}else if (inputValueTime === 'fortyFive') {
return 2700000;
}else if (inputValueTime === 'oneHour') {
 return 3600000;
}else if (inputValueTime === 'oneHalf') {
return 5400000;
}else if (inputValueTime === 'oneQuarter') {
return 6300000;
}else if (inputValueTime === 'twoHours') {
return 7200000;
}                   

answered question

What happens with the switch statement?

Actually, you don't have a name for your function. Should be something like function getInputValueTime(inputValuetime){... if else here}

3 Answers

7

I would use an object indexed by inputValueTime, whose values are the associated numbers:

const times = {
  thirty: 1800000,
  fourtyFive: 2700000,
  oneHour: 3600000,
  oneHalf: 5400000,
  oneQuarter: 6300000,
  twoHours: 7200000
};

function foo(inputValueTime) {
  return times[inputValueTime];
}

This will return undefined for inputValueTimes which are not in the object, just like your original code, for the most part - if inputValueTime can have Object.prototype properties (such as 'isPrototypeOf'), then use a hasOwnProperty check as well.

posted this
10

Why do you say a switch clause does not work ? Look at the code

function sample(inputValueTime) {
  switch (inputValueTime) {
    case 'thirty':
      return 1800000;
    case 'fortyFive':
      return 2700000;
    case 'oneHour':
      return 3600000;
    case 'oneHalf':
      return 5400000;
    case 'oneQuarter':
      return 6300000;
    case 'twoHours':
      return 7200000;
    default:
      return -1;
  }
}

console.log(sample("thirty"));
console.log(sample("fortyFive"));
console.log(sample("oneHour"));
console.log(sample("oneHalf"));
console.log(sample("oneQuarter"));
console.log(sample("twoHours"));

posted this
5

You should be able to use a switch statement.

function (inputValueTime) {
  switch (inputValueTime) {
    case 'thirty':
      return 1800000
    case 'fortyFive':
      return `270000
    case 'oneHour':
      return 3600000
    case 'oneHalf':
      return 5400000
    case 'oneQuarter'
      return 6300000
    case 'twoHours':
      return 7200000
  }
}

posted this

Have an answer?

JD

Please login first before posting an answer.