code: function normalizeSelection(ranges, primIndex) {
      var prim = ranges[primIndex];
      ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
      primIndex = indexOf(ranges, prim);
      for (var i = 1; i < ranges.length; i++) {
        var cur = ranges[i], prev = ranges[i - 1];
        if (cmp(prev.to(), cur.from()) >= 0) {
          var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
          var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
          if (i <= primIndex) --primIndex;
          ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
        }
      }
      return new Selection(ranges, primIndex);
    }
docs: Take an unsorted, potentially overlapping set of ranges, and build a selection out of it. 'Consumes' ranges array (modifying it).