判断最外层是否在范围内
function mergeRanges (ranges) {
// Sort the ranges based on the start date
ranges.sort((a, b) => a[0] - b[0]);
console.log('ssss')
console.log(ranges)
const merged = [];
for (let i = 0; i < ranges.length; i++) {
let [currentStart, currentEnd] = ranges[i];
// Check if the current range overlaps with the last merged range
if (merged.length && merged[merged.length - 1][1] >= currentStart) {
// If there's an overlap, merge the ranges
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], currentEnd);
} else {
merged.push([currentStart, currentEnd]);
}
}
return merged;
}
function checkCoverage (ranges, targetStart, targetEnd) {
// Merge all the given ranges
const mergedRanges = mergeRanges(ranges);
console.log(mergedRanges)
// Check if the merged ranges cover the target range
return (mergedRanges[0][0] == targetStart && mergedRanges[mergedRanges.length - 1][1] == targetEnd);
}
const ranges = [[6, 21], [3, 5], [11, 15], [17, 20]];
const targetStart = 1;
const targetEnd = 20;
// const ranges = [[new Date('2024-01-01').getTime(), new Date('2024-10-01').getTime()], [new Date('2024-11-02').getTime(), new Date('2024-11-11').getTime()]];
// const targetStart = new Date('2024-01-01').getTime();
// const targetEnd = new Date('2024-11-11').getTime();
console.log(checkCoverage(ranges, targetStart, targetEnd)); // true
判断是否连续
function areDateRangesContinuous (dateRanges) {
// 首先对数组进行排序
dateRanges.sort((a, b) => a[0] - b[0]);
console.log(dateRanges)
// 遍历排序后的数组
for (let i = 1; i < dateRanges.length; i++) {
// 如果当前日期范围的开始时间不是前一个日期范围的结束时间,则不连续
// 86400000
if (dateRanges[i][0] !== (dateRanges[i - 1][1] + 24 * 60 * 60 * 1000)) {
return false;
}
}
// 所有日期范围都连续
return true;
}
// 示例使用
const dateRanges = [
[new Date('2024-09-10').getTime(), new Date('2024-09-14').getTime()],
[new Date('2024-09-15').getTime(), new Date('2024-09-19').getTime()],
[new Date('2024-09-20').getTime(), new Date('2024-09-25').getTime()]
];
console.log(areDateRangesContinuous(dateRanges)); // 输出: true