Skip to content

Instantly share code, notes, and snippets.

@Peleke
Created December 23, 2016 21:10
Show Gist options
  • Save Peleke/e0f38df1b129b6529572082ba9b1c5e8 to your computer and use it in GitHub Desktop.
Save Peleke/e0f38df1b129b6529572082ba9b1c5e8 to your computer and use it in GitHub Desktop.
Solution to the problem of merging overlapping calendar appointments.
'use strict';
/******************************************************************************/
const overlaps = (previous, current) => current.startTime <= previous.endTime;
/******************************************************************************/
const merge_meetings = (most_recently_merged) => (next) =>
({ startTime : most_recently_merged.startTime, endTime : next.endTime })
/******************************************************************************/
const tap = (val, fn) => (arg) => (fn(arg), val)
// @impure
const rpush = (list) => (element) => tap(list, (element) => list.push(element))
/******************************************************************************/
const head = (list) => list[0]
const tail = (list) => list[list.length - 1]
const push_if_meetings_overlap = (merged) => (current) => {
const most_recently_merged = tail(merged),
length = merged.length;
return tap(merged, () => {
// @impure
if (overlaps(most_recently_merged, current))
merged[length - 1] = merge_meetings(most_recently_merged)(current)
else
merged.push(current)
})();
}
/******************************************************************************/
const merge_overlapping_meetings = (list_of_meetings) => {
list_of_meetings.sort((a, b) => a.startTime < b.startTime ? -1 : 1);
// @impure
return list_of_meetings.slice(1).reduce((merged, current, index) => {
return push_if_meetings_overlap(merged)(current);
}, [head(list_of_meetings)])
}
/******************************************************************************/
module.exports = merge_overlapping_meetings;
var a = [
{startTime: 0, endTime: 1},
{startTime: 3, endTime: 5},
{startTime: 4, endTime: 8},
{startTime: 10, endTime: 12},
{startTime: 9, endTime: 10},
]
console.log(merge_overlapping_meetings(a));
@Peleke
Copy link
Author

Peleke commented Dec 23, 2016

I should update nomenclature and curry overlaps for consistency, but you get the idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment