Detect overlapping periods in JS - how to make easy things complex

Detect overlapping periods in JS - how to make easy things complex

It’s unbelievable how sometimes we can do simple things so complicated. Fortunately in programming world we have something what is called „refactoring” and we really should do it as often as we can.

How to check if date periods are not overlapping? Maybe this way?

Ok, but of course whole magic is in areDatesOverlappingValidationAlgorithm* function, so let’s look at its implementation.

First variant which I’ve founded in the project looks like this:

I would say it’s complex and completely unreadable. Additionally, as you can guess, this algorithm had a bug (one of conditions was missing).

Can we make it simpler? Of course we can!

First, let’s do sth with null values and organize conditions

  1. null values – if there is a null value in dateTo or existingDateTo variable we assume this is a period with no end (from some date to infinity). Instead of checking in every condition if date is null, we can check it once and if so, assign max date value
  2. conditions – just get rid of them, get piece of paper and do it again 🙂

After first step, we’ve got:

Next, we can even do sth more with still quite complex conditions in last if statement. Thanks to mathematical logic and what’s more important Stackoverflow answer we can replace whole last if statement with just one line of code:

Finally we can go back to validateDates function, take few things out of the for loop for optimization purpose and after all changes, our method looks like this:

That’s it. It’s simple, it’s readable.

PS. You can find whole code with few test cases below, just put it to .html file and run in your browser: