Here is a hypothetical algorithm for sorting and combining intersecting time segments:
First, sort all objects based on the start date of the time segment. Create a new structure by iterating through the sorted structure as follows: 2.1. Before the loop, set up a variable to temporarily store intersecting time intervals. Also, initialize an array to accumulate intersecting segments, starting with the first time segment. The loop begins from the second time period. 2.2. Check if the current time segment intersects with the next one. In other words, if the start of the next date is before the end of the current one. 2.2.1. If there is an intersection, update the end in the time structure with the end of the next segment. 2.2.2. If there is no intersection, push the result into the array. Add the subsequent time period to the accumulation variable. The loop continues for the segment after the next (although this step may be skipped).
const data = [ { "from":"01/01/2020", "to":"01/06/2020" }, { "from":"01/10/2020", "to":"01/10/2020" } ]
const monthToString = month => {
const months = {
'01': 'Jan',
'02': 'Feb',
'03': 'Mar',
'04': 'Apr',
'05': 'May',
'06': 'Jun',
'07': 'Jul',
'08': 'Aug',
'09': 'Sep',
'10': 'Oct',
'11': 'Nov',
'12': 'Dec',
}
return months[month] || month
}
const result = Object.entries(data.reduce((res, {from, to}) => {
const [monthFrom, day, year] = from.split('/')
const [m, dayTo, y] = to.split('/')
const month = monthToString(m)
return {
...res,
[month]: [...(res[month] || []), [day, dayTo]]
}
}, {})).map(([month, days]) => `${month} ${days.map(([from, to]) => `${parseInt(from)}-${parseInt(to)}`).join(', ')}`).join('\n')
console.log(result)
Is there a way to combine dates when they intersect?