2012-02-22 92 views
0

我有JSON的列表值的Javascript搜索範圍

[{'start_day':1,'start_hour':1,'end_day':1,'end_hour':2}, 
{'start_day':1,'start_hour':4,'end_day':1,'end_hour':6}, 
{'start_day':1,'start_hour':9,'end_day':1,'end_hour':11}] 

現在在Javascript中我有一個表,讓我更多的這些添加到表中。我可以做到這一點沒有問題,但我正在尋找的是。是否有任何代碼可以讓我搜索以確保用戶沒有輸入重疊的日期時間範圍。類似於SQL之間的命令。

回答

0

由於您指的是7天x 24小時範圍,因此創建一個包含所有值的表格可能很有用。這樣做的好處是,您不必爲每個新元素重複計算。相反,你可以添加一個計數器。

在你的情況下,計數器應該始終爲零或一(因爲日期可能不重疊,每個定義)。但是,可以使用相同的函數也可以使用來確定給定一組對象是否有重疊。然後,其中一個計數器大於一個。

代碼(演示:http://jsfiddle.net/EtaJE/1/):

// Initialize list and variables. 
var totalHours = 7*24; 
var dates = [];        // Empty list 
for (var i=0; i<totalHours; i++) dates.push(0);// Fill list with zeros 

/* @param listi object { start_day ; end_day ; start_hour ; end_hour } 
* @param one number Recommended values: 1 (add), -1 (remove) 
*/ 
function addDate(listi, one) { 
    one = +one === one ? one : 1; // Make sure that one is a number. 

    var listi = list[i]; 
    if (listi.start_day <= listi.end_day) { 
     var start = listi.start_day * 24 + listi.start_hour; 
     var end = listi.end_day * 24 + listi.end_hour; 
     for (var j=start; j<end; j++) { 
      dates[j] += one; // Increase counter by one 
     } 
    } else { 
     var start = listi.start_day * 24 + listi.start_hour; 
     var end = listi.end_day * 24 + listi.end_hour; 
     for (var j=0; j < end; j++) { 
      dates[j] += one; // Increase counter by one 
     } 
     for (var j=start; j<totalHours; i++) { 
      dates[j] += one; // Increase counter by one 
     } 
    } 
} 

/* 
* @param object { start_day ; end_day ; start_hour ; end_hour } 
*/ 
function doesDateOverlap(listi) { 
    if (listi.start_day <= listi.end_day) { 
     var start = listi.start_day * 24 + listi.start_hour; 
     var end = listi.end_day * 24 + listi.end_hour; 
     for (var j=start; j<end; j++) { 
      if (dates[j]) return true; // Not zero, overlapping! 
     } 
    } else { 
     var start = listi.start_day * 24 + listi.start_hour; 
     var end = listi.end_day * 24 + listi.end_hour; 
     for (var j=0; j < end; j++) { 
      if (dates[j]) return true; // Not zero, overlapping! 
     } 
     for (var j=start; j<totalHours; i++) { 
      if (dates[j]) return true; // Not zero, overlapping! 
     } 
    } 
    return false; // At this point: No overlap, so OK. 
} 


// Parse the values from the JSON list. Example: 
var list = [{'start_day':1,'start_hour':1,'end_day':1,'end_hour':2}, 
      {'start_day':1,'start_hour':4,'end_day':1,'end_hour':6}, 
      {'start_day':1,'start_hour':9,'end_day':1,'end_hour':11}] 
for (var i=0; i<list.length; i++) { 
    addDate(list[i], 1); 
} 

// Example 
if (doesDateOverlap({'start_day':1,'start_hour':1,'end_day':1,'end_hour':11})){ 
    alert('Overlap!'); 
} 
+0

這工作的程度。我的星期從 星期日0到星期六6.如果我在星期五開始時間並將它運行到星期二2.我會更新腳本http://jsfiddle.net/EtaJE/1/ – TheMonkeyMan 2012-02-22 13:06:22

+0

@Deano更新回答。請注意,我的時間範圍從0到23。 – 2012-02-22 14:25:02