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:




Komponenty – podstawowa składowa współczesny... Jeśli programista zajmujący się w dzisiejszych czasach front-endem zostałby zapytany o to co łączy popularne obecnie biblioteki i frameworki służące...
Getting started on ASP.NET Core & React – epi... Contents Episode 1 – Introduction Episode 2 – Backend / Infrastructure Episode 3 – Frontend Setup Episode 4 - Data flow Episode 5 –...
Operatory porównania w języku JavaScript Porównywanie wartości zmiennych to jedna z podstawowych operacji każdego języka programowania. Często przyjdzie nam sprawdzić czy w danej kolekcji...
Page Object, WebdriverIO advanced concepts –... Page Object pattern is well-known in the world of test automation. Fortunately the new version (v4) of test automation framework was ...