Merge Overlapping Intervals

#!/usr/bin/env mocha

function m(intervals) {

//Sort the intervals
  intervals.sort(function(a, b) {
    return a[0] - b[0];
  });

//Merged intervals
  var r = [];

//Iterate over the intervals
  for (var i = 0, len = intervals.length; i < len; ) {

    var end = intervals[i][1];

//Now find the interval end
    for (var j = i + 1; j < len && end >= intervals[j][0]; j++) {
      if (intervals[j][1] > end) {
        end = intervals[j][1];
      }
    }

    r.push([intervals[i][0], end]);

    i = j;
  } 

  return r;
}

var assert = require("assert");

describe('mergeIntervals', function(){
    it('should merge all the contigous intervals', function() {
      assert.deepEqual([ [1, 9] ], m([ [6,8], [1,9], [2,4], [4,7] ]));
      assert.deepEqual([ [1, 8] ], m([ [6,8],[1,3],[2,4],[4,7] ]));
      assert.deepEqual(
       [ [1, 3], [4, 6], [7, 9], [10, 13] ], m([ [1,3],[7,9],[4,6],[10,13]]
      ));
      assert.deepEqual(
       [ [1,4], [5, 8]], m([[1,3], [2,4], [5,7], [6,8] ]
      ));
    })
})