So, I have an object with two ints representing years, like this:
const targetRange = { from: 2015, to: 2020 };
Then I have an array with other ranges, like this:
const currentRanges = [
{ from: 2003, to: 2006 },
{ from: 2006, to: 2010 },
{ from: 2010, to: 2014 },
{ from: 2014, to: 2019 },
]
I want to make a function rangesCollide
that checks if the target range collides with any of the current ranges.
Examples:
rangesCollide({ from: 2010, to: 2015 }, { from: 2007, to: 2010 }); // false
rangesCollide({ from: 2010, to: 2015 }, { from: 2007, to: 2011 }); // true
rangesCollide({ from: 2010, to: 2015 }, { from: 2010, to: 2010 }); // false
rangesCollide({ from: 2010, to: 2015 }, { from: 2010, to: 2013 }); // true
rangesCollide({ from: 2010, to: 2015 }, { from: 2011, to: 2014 }); // true
rangesCollide({ from: 2010, to: 2015 }, { from: 2015, to: 2015 }); // false
rangesCollide({ from: 2010, to: 2015 }, { from: 2014, to: 2018 }); // true
rangesCollide({ from: 2010, to: 2015 }, { from: 2015, to: 2020 }); // false
rangesCollide({ from: 2010, to: 2015 }, { from: 2018, to: 2022 }); // false
I can't wrap my head about how I could make it work.
Ok, I found this:
Find out if two line segments intersect
Which is basically the same problem, this is the solution:
function overlap(A1,A2,B1,B2) {
return A1<=B1?A2>=B1:B2>=A1;
}
But I had to change the <= and >= to < and > respectively.