Reputation: 2174
I am working on a project in which I have to flag certain holidays throughout the year. I have determined the specific holidays, however i am having trouble on the front end allowing for the proper message to render, and I feel as if there is a shorter way of doing this, but not sure.
My code below is here. This is written in a controller, and i am using coffeescript, but for the sake of this question, converted the coffee script into javascript.
day = new Date()
month1 = moment()
var date, holiday2, month, weeknum;
date = day.getDay();
month = month1.month() + 1;
weeknum = Math.ceil(date / 7) + 1;
holiday2 = month + "/" + weeknum + "/" + date;
if (holiday2 === "1/3/1") {
vm.typedholiday = "Martin Luther King Day"; }
if (holiday2 === "2/3/1") {
vm.typedholiday = "Washington's Birthday"; }
if (holiday2 === "5/3/6") {
vm.typedholiday = "Armed Forces Day"; }
if (holiday2 === "9/1/1") {
vm.typedholiday = "Labor Day"; }
if (holiday2 === "10/2/1") {
vm.typedholiday = "Columbus Day"; }
if (holiday2 = "11/4/4") {
vm.typedholiday = "Thanksgiving Day"; }
vm.message = true
.row.holiday-banner{ 'ng-if' => "vm.message" }
.col-xs-12
.holiday-body.text-center
%h3 We are currently closed due to {{ vm.typedholiday }}.
So with this I have two questions. The date of me writing this question does actually happen to be Columbus Day. However, I continue to have Thanksgiving Day rendered instead of Columbus Day. I can't figure out why this is the case. If there is something with my code that would cause that, please let me know. I am also wondering if it would it be better to use the JS 'switch' method instead? if so, how?
Upvotes: 0
Views: 39
Reputation: 3042
Maybe you should consider this :
...
holiday2 = month + "/" + weeknum + "/" + date;
var specialDays = {
"1/3/1" : "Martin Luther Kind Day" ,
"2/3/1" : "Washington's Birthday" ,
"5/3/6" : "Armed Forces Day" ,
"9/1/1" : "Labor Day" ,
"10/2/1" : "Columbus Day" ,
"11/4/4" : "Thanksgiving Day" ,
}
vm.typedholiday = specialDays[ holiday2 ];
vm.message = true
...
I found this more readable, and easy to extend !
Upvotes: 0
Reputation: 46341
Your value is overwritten since your last if
isn't using a comparison operator, it's using an assignment operator:
if (holiday2 = "11/4/4")
All this does is assign the string "11/4/4"
to holiday2
and since that is a truthy value, continues with the next statement which overrides vm.typedholiday
with "Thanksgiving Day"
.
The obvious fix is:
if (holiday2 === "11/4/4")
Upvotes: 3
Reputation: 30330
You could use switch
instead - it doesn't make much difference. If your project has a styleguide, do what that says. If not, choose the style you prefer.
If you did use switch
, it'd look something like this:
switch (holiday2) {
case "1/3/1":
vm.typedholiday = "Martin Luther Kind Day";
break;
case "2/3/1":
vm.typedholiday = "Washington's Birthday";
break;
// more cases
}
Upvotes: 0