jonmrich
jonmrich

Reputation: 4323

Condensing similar IF statements

I know there has to be a better way than this:

if (mon_open_close_hours=='12:00-12:00'){
    mon_open_close_hours='24hrs';
}
if (tue_open_close_hours=='12:00-12:00'){
    tue_open_close_hours='24hrs';
}
if (wed_open_close_hours=='12:00-12:00'){
    wed_open_close_hours='24hrs';
}
if (thu_open_close_hours=='12:00-12:00'){
    thu_open_close_hours='24hrs';
}
if (fri_open_close_hours=='12:00-12:00'){
    fri_open_close_hours='24hrs';
}
if (sat_open_close_hours=='12:00-12:00'){
    sat_open_close_hours=['24hrs'];
}
if (sun_open_close_hours=='12:00-12:00'){
    sun_open_close_hours=['24hrs'];
}

Is there a way to condense this somehow?

I've tried this, but it returns '12:00-12:00' for everything

var $variables = [mon_open_close_hours,tue_open_close_hours,wed_open_close_hours,thu_open_close_hours,fri_open_close_hours,sat_open_close_hours,sun_open_close_hours];
     $variables.map(function(val) {
        if(val=='12:00-12:00'){
            val=['24hrs'];
        }
    })

Upvotes: 0

Views: 61

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

As I have already said, it is better to store open-close hours in an array of weekdays, not in separate variables. In this case, you will be able to operate with them using for-loops.

However, if we talk specifically about your case, then you use Array.prototype.map incorrectly.
Mapping function should return value, reassigning the reference to its argument in a local scope won't affect anything.
Also, map does not change the original array, it returns a new one, so you need to assign this result to a new variable or to the original one.

Use this:

var openCloseHours = [
  "09:00-15:00", 
  "09:00-18:00", 
  "09:00-18:00", 
  "09:00-18:00", 
  "09:00-18:00", 
  "12:00-12:00", 
  "12:00-12:00"
];

openCloseHours = openCloseHours.map(function(val) {
  if (val == '12:00-12:00'){
    return ['24hrs'];
  }

  return val;
});

console.log(openCloseHours);

Upvotes: 2

Nisarg Shah
Nisarg Shah

Reputation: 14531

If you truly want to improve it, you'd have to change the way you store and process data. This might require changes to the way your DOM is used, and how you interact with your backend. But it is certainly better than having 7 different variables for each day.

var open_close_hours = {};
var days = ["mon","tue","wed", "thu", "fri", "sat", "sun"];

// Some code that sets the properties.
// ...

// Conditions.

days.forEach(function(day){
  if(open_close_hours[day] == '12:00-12:00') {
    open_close_hours[day] = ['24hrs'];
  }
});

Upvotes: 4

Related Questions