只要您的日历记录以某种方式排序,您就可以对其应用二进制搜索算法。如果您将日期保存为时间戳而不是字符串,它可能会使比较更快(尽管对于您当前的格式,字符串比较也可以)。
按“周”索引您的日历可能更优雅。就像是
{
"Week 1": ['2011-04-26', '2011-05-02', '2010 - 11'],
"Week 2": ['2011-05-03', '2011-05-09', '2010 - 12'],
...
}
请注意,从您的calendar
数组创建此查找对象的复杂度为 O(n),因此如果您只需要搜索一条记录,即使对原始数组进行线性搜索也会更快。
原始数组的示例算法:
var calendar = [
['2011-04-26', '2011-05-02', 'Week 1', '2010 - 11'],
['2011-05-03', '2011-05-09', 'Week 2', '2010 - 12'],
...
];
function getRecord(date) {
var l = 0,
r = calendar.length-1;
while (l <= r) {
var m = ~~(l + (r-l)/2);
var comp = comparefn(this[m]);
if (calendar[m][1] < date) // last day of week before date
l = m+1;
else if (calendar[m][0] > date) // first day of week after date
r = m-1;
else // week found
return calendar[m];
}
// I'm not quite sure what happens when a date lies between two weeks in the calendar
return null;
}