3 ms·
Just a followup on my "amazing and scary" comment. The "amazing" part is a genuine compliment: you found a pattern in the number of days in each month that I ne
by Stratoscope 14y ago
Just a followup on my "amazing and scary" comment. The "amazing" part is a genuine compliment: you found a pattern in the number of days in each month that I never noticed (the 'flip' trick). Being able to see these kinds of patterns and take advantage of them is an invaluable skill in programming.
The problem here, of course, is that it makes the code a lot harder to understand. To understand and verify the function, I'd start by writing out a table of the days in each month while reciting the "30 days hath September" rhyme. :-) Then I'd have to go through all the the flip and non-flip cases in the code and compare against my table.
Let's imagine that JavaScript didn't have convenient date calculations so we couldn't use the updated function I posted above. If that were the case, what would be a simpler way to code the function? Just use the table of months directly. After all, there are only 12 months to deal with, so it's very simple:
getCountDays: function( year, month ) {
var monthDays = [
31, 0, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31
];
return monthDays[month] || getFebDays( year );
},
where getFebDays() handles all the special cases for leap years ( /4, /100, /400, etc.)
Now, with the exception of February, it's trivial to see at a glance if the function is correct.