Last active
June 25, 2024 23:54
-
-
Save sytabaresa/dda343f5ca9494866793ce6b0f4385a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dayjs from 'dayjs'; | |
import minMax from 'dayjs/plugin/minMax.js' | |
dayjs.extend(minMax); | |
function findDifference(list1, list2) { | |
const result = {}; | |
// Loop through each range in list1 | |
while (list1.length > 0) { | |
const range1 = list1.pop() | |
const r1 = range1.map(r => dayjs(r)); | |
const [start1, end1] = r1; | |
// Check for overlaps or complete containment in list2 | |
let foundOverlap = false; | |
let splitted = false; | |
for (const range2 of list2) { | |
const [start2, end2] = range2.map(r => dayjs(r)); | |
// Check if range1 completely contains range2 | |
if (start1 < start2 && end1 > end2) { | |
splitted = true | |
// Add non-overlapping part before range2 | |
if (start1 < start2) { | |
list1.push([start1, start2]); | |
} | |
// Add non-overlapping part after range2 | |
if (end1 > end2) { | |
list1.push([end2, end1]); | |
} | |
continue; // No need to check further overlaps for a splitted range1 | |
} | |
// Check if there's an overlap | |
if (start1 < end2 && end1 > start2) { | |
foundOverlap = true; | |
// Add non-overlapping parts of range1 | |
if (start1 < start2) { | |
list1.push([start1, dayjs.min(end1, start2)]); | |
} | |
if (end1 > end2) { | |
list1.push([dayjs.min(start1, end2), end1]); | |
} | |
continue; // No need to check further overlaps for this range1 | |
} | |
} | |
// If no overlap or splits found in list2, add the entire range1 to result | |
if (!foundOverlap && !splitted) { | |
result[r1.map(r => r.toISOString())] = true; | |
} | |
} | |
// return result | |
// console.log(Object.keys(result)) | |
return Object.keys(result).map(r => r.split(','))//.map(e => dayjs(e))) | |
} | |
// Example usage | |
const list1 = [['2024-06-20', '2024-06-25'], ['2024-06-30', '2024-07-05']]; | |
const list2 = [['2024-06-22', '2024-06-23'], ['2024-06-23', '2024-06-25'], ['2024-07-02', '2024-07-08']]; | |
const difference = findDifference(list1, list2); | |
console.log(difference); | |
// output [ | |
// [ '2024-06-30T05:00:00.000Z', '2024-07-02T05:00:00.000Z' ], | |
// [ '2024-06-20T05:00:00.000Z', '2024-06-22T05:00:00.000Z' ] | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment