import parseTimeToMinutes from './parseTimeToMinutes.js' /** * Merges overlapping intervals in an array of time intervals. * * This function takes an array of time intervals, where each interval is represented as a tuple of * start and end times in "HH:MM" format or as a single number in hours. It merges any overlapping * intervals to produce a minimal set of intervals. * * @param {Array>} intervals - An array of tuples representing the time intervals. * @returns {Array>} A new array of tuples with merged intervals in "HH:MM" format. */ const mergeIntervals = (intervals) => { // Convert all intervals to minutes for easier comparison and sorting. const parsedIntervals = intervals.map(([ start, end, ]) => [ parseTimeToMinutes(start), parseTimeToMinutes(end), ]) // Sort intervals based on the start time to prepare for merging. parsedIntervals.sort(( a, b, ) => a[0] - b[0]) const merged = [] // This array will hold the merged intervals. let currentInterval = parsedIntervals[0] // Start with the first interval. // for (let i = 1; i < parsedIntervals.length; i++) { parsedIntervals.forEach((interval) => { const [ currentStart, currentEnd, ] = currentInterval const [ nextStart, nextEnd, ] = interval if (currentEnd >= nextStart) { // If the current and next intervals overlap, merge them. currentInterval = [ currentStart, Math.max( currentEnd, nextEnd, ), ] } else { // If they don't overlap, push the current interval to the result and move to the next. merged.push(currentInterval) currentInterval = interval } }) // Don't forget to add the last interval to the result. merged.push(currentInterval) // Convert the merged intervals back to "HH:MM" format. return merged.map(([ start, end, ]) => [ `${Math.floor(start / 60) .toString() .padStart( 2, '0', )}:${(start % 60).toString().padStart( 2, '0', )}`, `${Math.floor(end / 60) .toString() .padStart( 2, '0', )}:${(end % 60).toString().padStart( 2, '0', )}`, ]) } /** * Example usage: * const intervals = [["04:04", "15:01"], ["8:00", "10:30"], ...]; * const mergedIntervals = mergeIntervals(intervals); * console.log(mergedIntervals); // Prints the merged intervals */ export default mergeIntervals