Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Last active January 21, 2020 13:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mxriverlynn/63241c2064471b9d5b6a to your computer and use it in GitHub Desktop.
Save mxriverlynn/63241c2064471b9d5b6a to your computer and use it in GitHub Desktop.
checking for date range overlap
// this function takes an array of date ranges in this format:
// [{ start: Date, end: Date}]
// the array is first sorted, and then checked for any overlap
function overlap(dateRanges){
var sortedRanges = dateRanges.sort((previous, current) => {
// get the start date from previous and current
var previousTime = previous.start.getTime();
var currentTime = current.start.getTime();
// if the previous is earlier than the current
if (previousTime < currentTime) {
return -1;
}
// if the previous time is the same as the current time
if (previousTime === currentTime) {
return 0;
}
// if the previous time is later than the current time
return 1;
});
var result = sorted.reduce((result, current, idx, arr) => {
// get the previous range
if (idx === 0) { return result; }
var previous = arr[idx-1];
// check for any overlap
var previousEnd = previous.end.getTime();
var currentStart = current.start.getTime();
var overlap = (previousEnd >= currentStart);
// store the result
if (overlap) {
// yes, there is overlap
result.overlap = true;
// store the specific ranges that overlap
result.ranges.push({
previous: previous,
current: current
})
}
return result;
// seed the reduce
}, {overlap: false, ranges: []});
// return the final results
return result;
}
var r1 = {
start: new Date("2/4/2001"),
end: new Date("7/1/2002")
};
var r2 = {
start: new Date("7/2/2002"),
end: new Date("2/4/2003")
};
// start date overlaps with end date of previous
var r3 = {
start: new Date("2/4/2003"),
end: new Date("5/12/2007")
};
var ranges = [r1, r3, r2];
var output = JSON.stringify(overlap(ranges), null, 2)
console.log(output);
{
"overlap": true,
"ranges": [
{
"previous": {
"start": "2002-07-02T05:00:00.000Z",
"end": "2003-02-04T06:00:00.000Z"
},
"current": {
"start": "2003-02-04T06:00:00.000Z",
"end": "2007-05-12T05:00:00.000Z"
}
}
]
}
@Jacse
Copy link

Jacse commented Feb 27, 2016

shouldn't sorted in line 26 be replaced with sortedRanges?

@openp2pdesign
Copy link

@Jacse agree

@DamirLuketic
Copy link

Yes, I also change line 26, but now work perfectly. Thx. derickbailey

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