title: Calculate overlaps of time ranges with time range
body: <p>I try to calculate the amount (in minutes) of overlaps between a given time range and an array of time ranges.</p>
  
  <p>First I order the ranges by start time, and filter them, if they not overlap with the range.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const range = ["2019-11-06 08:00", "2019-11-06 17:00"]; // 9h
  const ranges = [
    ["2019-11-06 00:00", "2019-11-06 10:00"],
    ["2019-11-06 22:00", "2019-11-06 24:00"],
    ["2019-11-06 09:00", "2019-11-06 12:00"]
  ]
  
  function calculateOvelappings(range, ranges) {
    const start = moment(range[0])
    const end = moment(range[1])
    let overlaps = 0
    // order ranges by start time
    ranges = ranges.sort((a, b) =&gt; moment(a[0]).unix() - moment(b[0]).unix())
    for(let i = 0; i &lt; ranges.length; i++) {
      const rangeStart = moment(ranges[i][0])
      const rangeEnd = moment(ranges[i][1])
      if (rangeEnd.isBefore(start) || rangeStart.isAfter(end)) {
        continue;
      }
      
    }
    return overlaps
  }
  
  
  console.log(calculateOvelappings(range, ranges))</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"&gt;&lt;/script&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The right answer for overlaps would be 4 hours. The input range starts at 08:00 in intersects with range 1 (from the array) till 10:00 (2 hours). Range 2 is irrelevant. Range 3 overlaps with the input range from 09:00 to 12:00, but from 09:00 to 10:00 is already calculated from range 1. Therefor 2 + (3 - 1) = 4 hours. </p>
  
  <p>Is there an elegant algorithm, to calculate this?
  Any help would be appreciated, a pseudo code, or even a theoretical answare.</p>
  
  <p>Here is a JsBin: <a href="https://jsbin.com/noyuhekura/1/edit?js,console" rel="nofollow noreferrer">https://jsbin.com/noyuhekura/1/edit?js,console</a></p>