這不是緊湊其他兩個解決方案,但他們分享相同的邏輯。 您可以使用排序的一組日期來存儲您的假期。
所以您的解決方案應該是這樣:
var holiday = [new Date('2014-01-01'), new Date('2014-07-04'),new Date('2014-12-24'), new Date('2014-12-25')];
var startDate = new Date('2014-08-01');
var endDate = new Date('2014-12-30');
function getHolidays(start, end){
//create and initialize a SortedSet object
var holidays = new SortedSet(holiday);
var startIndex = holidays.bisect_left(startDate);
var endIndex = holidays.bisect_left(endDate);
return holidays.getSubSet(startIndex, endIndex).toArray();
}
//utility function to get the date as a string in the preferred format
function dateToMyString(date){
return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}
//get array of dates
var h = getHolidays(startDate, endDate);
//convert to array of strings
h.forEach(function(date, index, array){
h[index] = dateToMyString(date);
});
現在的SortedSet可能是這個樣子(這是上午6:00,所以我可以在這裏犯了一個錯誤:)):
function SortedSet(arr){
var set = new Array();
//gets insertion position for item
this.bisect_left = function(item){
var length = set ? set.length : -1;
var l = 0, r = length, p;
if(r < 1){
return -1;
}
while(r > l){
p = parseInt(l + (r - l)/2);
if (set[p] < item){
l = p + 1;
} else {
r = p;
}
}
return l;
};
//adds element to set in sorted order
this.add = function(item){
var pos = this.bisect_left(item);
if(pos === -1 || pos === set.length){
set.push(item);
return;
}
if (set[pos] === item){
return;
}
set.splice(pos, 0, item);
};
//gets item at given index
this.at = function(index){
return set[index];
};
//returns subset
this.getSubSet = function(startIndex, endIndex){
return new SortedSet(set.slice(startIndex, endIndex));
};
//returns the set var
this.toArray = function(){
return set;
}
//initialize the set array
if(arr && arr instanceof Array){
for(var i = arr.length; i--;){
this.add(arr[i]);
}
}
}
getHolidays()是什麼意思?你的問題相當模糊(實際上,你的問題是什麼?)。 – orange 2014-12-08 02:20:20
該函數可以返回假期列表。我不知道從哪裏開始,所以我沒有在裏面放任何東西。 – BonJon 2014-12-08 02:24:12