我有一个json,如:
var availabilitys = [
{
"date": "2015-08-15",
"timeslots": [
{
"id": 52,
"date": "2015-08-15",
"start_time": "2015-08-15T10:00:50.836Z",
"end_time": "2015-08-15T09:00:50.837Z"
}
]
},
{
"date": "2015-08-16",
"timeslots": [
{
"id": 53,
"date": "2015-08-16",
"start_time": "2015-08-16T06:00:00.885Z",
"end_time": "2015-08-16T08:00:00.885Z"
},
{
"id": 72,
"date": "2015-08-16",
"start_time": "2015-08-16T07:00:00.885Z",
"end_time": "2015-08-16T08:00:00.885Z"
}
]
},
{
"date": "2015-08-17",
"timeslots": [
{
"id": 54,
"date": "2015-08-17",
"start_time": "2015-08-17T11:25:50.893Z",
"end_time": "2015-08-17T10:25:50.893Z"
},
{
"id": 54,
"date": "2015-08-17",
"start_time": "2015-08-17T11:25:50.893Z",
"end_time": "2015-08-17T10:25:50.893Z"
}
]
}
];
我想查看时段的开始和结束时间。 - 开始时间小于时间段中的结束时间 - 在一天中下一个时隙的开始时间必须大于或等于结束时间上一个时间段
希望大家帮助我,谢谢。
答案 0 :(得分:0)
如果满足两个条件(结束时间之前的开始时间和非重叠的插槽),这是一个简单的函数,它接收availabilitys
数组并返回Boolean
:true
对于所有时间段,false
否则。
validateAvailabilities(availabilitys)
为您的示例false
数组正确返回availabilitys
。
function validateAvailabilities(avails) {
return avails.every(dayValidates);
function dayValidates(day) {
return day.timeslots.every(startBeforeEnd) &&
day.timeslots.every(timeslotsDontOverlap);
function startBeforeEnd(timeslot) {
return toTime(timeslot.start_time) <= toTime(timeslot.end_time);
}
function timeslotsDontOverlap(slot, i, slots) {
// A timeslot does not overlap if its the first one, or its start time
// is on or after the previous slot's end time.
return i === 0 ||
toTime(slot.start_time) >= toTime(slots[i - 1].end_time);
}
function toTime(dateStr) {
return new Date(dateStr).getTime();
}
}
}
注意:它假定每天的时段数组已按时间升序排序。如果不是这种情况,则会导致重叠时隙检查错误。