Don't write your own date functions. Don't write your own date functions. Erich sends us this beauty, which is meant to adjust a date based on the starting day of the week- which might be a day other than Sunday, for a variety of reasons.
_getAdjustedDay: function(/*Date*/dateObj) {
//summary: used to adjust date.getDay() values to the new values based on the current first day of the week value
var days = [0,1,2,3,4,5,6];
if(this.weekStartsOn>0){
for(var i=0;i<this.weekStartsOn;i++){
days.unshift(days.pop());
}
}
return days[dateObj.getDay()]; // Number: 0..6 where 0=Sunday
}
The getDay
function returns a numeric day of the week: 0 for Sunday, 1 for Monday, etc. In this application, users might want their week to start on a different day- for example, many want Monday to be the first day. This function will do that adjustment, and the way it does it is TRWTF.
They start with an array of 7 days
, and then rotate the array using unshift
and pop
. Pop the first element, unshift it into the last element. Then, when we index by the day of the week, it'll return the adjusted day.
Of course, this is just the long way around to doing some pretty basic arithmetic- the rotation, in this case, is just a modulus done the hard way.
This was not internal code, either. This was in a third party library that, at the time Erich found the code, was widely used.