title: Algorithm to sum ranges that lie within another separate range
body: <p>I have two sets of ranges, one is a single range of any length (A) and the other is a set of ranges (B) some or parts of which may or may not lie within the single range (A).</p>
  
  <p>I need to calculate the sum of the ranges in (B) - whole or partial - that lie within the single range (A).</p>
  
  <p>I am using Javascript.</p>
  
  <p>Examples:</p>
  
  <pre><code>A = [20,40]&lt;br&gt;
  B = [14,22],[24,27],[31,35],[38,56]&lt;br&gt;
  Result = 2+3+4+2 = 11&lt;br&gt;
  
  A = [120,356]&lt;br&gt;
  B = [234,567]&lt;br&gt;
  Result = 122&lt;br&gt;
  </code></pre>
  
  <p>I need an algorithm/function that will return the resulting sum.</p>
  
  <p>I used an excelent range merging algorithm posted here previously, I'm hoping for a similar elegant solution for this problem.</p>
  
  <p>(Appologies if there has been a misunderstanding.
  I have been working on a function but my maths in a coding context isn't good, so my solution was to use non-maths code (It would be embarassing to post it here!). I hoped to get some help here to create a compact maths based solution)</p>