我有一组[start_time, end_time]
时间范围如下:
let timeSegments = [];
timeSegments.push(["02:00", "07:00"])
timeSegments.push(["03:00", "04:00"])
这些时间段重叠,因为2AM - 7AM
包含3AM - 4AM
同样地:
let timeSegments = [];
timeSegments.push(["14:00", "18:00"])
timeSegments.push(["15:00", "19:00"])
2PM
至6PM
与3PM
重叠至7PM
。
我正在使用momentjs库,并且想知道一种方法来确定我的timeSegments数组是否包含任何重叠的timeSegments? timeSegments数组最多可包含10个[start_time, end_time]
对。谢谢!
我只想知道是否有任何段重叠(真/假),我不需要知道哪些段重叠等。
答案 0 :(得分:9)
您可以timeSegments
对start_time
进行排序(使用Array.prototype.sort
)并遍历排序列表并检查当前timeSegment的end_time
是否大于{ {1}}下一个。
如果发生这种情况,则会有重叠。
答案 1 :(得分:8)
您可以使用moment-range插件。您可以使用moment.range
函数传递时刻对象作为输入来创建范围(使用moment(String, String)
解析输入字符串)。然后,您可以使用overlap
方法检查两个范围是否重叠。
这是一个实时样本:
window['moment-range'].extendMoment(moment);
let overlap = (timeSegments) => {
let ret = false;
let i = 0;
while( !ret && i<timeSegments.length-1 ){
let seg1 = timeSegments[i];
let seg2 = timeSegments[i+1];
let range1 = moment.range( moment(seg1[0], 'HH:mm'), moment(seg1[1], 'HH:mm'));
let range2 = moment.range( moment(seg2[0], 'HH:mm'), moment(seg2[1], 'HH:mm'));
if( range1.overlaps(range2) ){
ret = true;
}
i++;
return ret;
}
};
let timeSegments = [];
timeSegments.push(["02:00", "07:00"])
timeSegments.push(["03:00", "04:00"])
console.log( overlap(timeSegments) ); // true
timeSegments = [];
timeSegments.push(["14:00", "18:00"])
timeSegments.push(["15:00", "19:00"])
console.log( overlap(timeSegments) ); // true
timeSegments = [];
timeSegments.push(["14:00", "18:00"])
timeSegments.push(["19:00", "21:00"])
console.log( overlap(timeSegments) ); // false
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/3.0.3/moment-range.min.js"></script>
&#13;
答案 2 :(得分:0)
您可以参考以下代码的参考表格。我正在使用核心JavaScript。
<script>
var obj = [{ "from": "08:00", "to": "9:01" }, { "from": "18:45", "to": "19:00" }, { "from": "08:00", "to": "09:00" }, { "from": "12:00", "to": "14:00" }];
obj = sortTime(obj);
console.log(obj);
if (checkoverlapping(obj)) {
alert("yes time overlaps");
} else {
alert("No overlapping")
}
function sortTime(obj) {
obj.sort(function (a, b) {
KeyA = minuteValue(a.from);
KeyB = minuteValue(b.from);
if (KeyA < KeyB) return -1;
else if (KeyA > KeyB) return 1;
else {
a = minuteValue(a.to);
b = minuteValue(b.to);
if (a < b) return -1;
if (a > b) return 1;
return 0
}
})
return obj;
}
function minuteValue(time) {
time = time.split(":");
return (time[0] * 60) + (time[1] * 1);
}
function checkoverlapping(obj) {
let previous = obj[0], current, overlapping = false;
for (let i = 1; i < obj.length; i++) {
current = obj[i]
if (minuteValue(previous.to) > minuteValue(current.from)) {
overlapping = true;
break;
}
}
return overlapping;
}
</script>