-6

I need to split range from main range. For example

var start = 0;
var end = 100;
var ranges = [
 { start: 25, end: 50 },
 { start: 60, end: 70 }
]

my expected output is,

{ start: 0, end: 24},
{ start: 51, end: 59},
{ start: 71, end: 100}

how to acheive this?

Akbar Basha
  • 1,168
  • 1
  • 16
  • 38
  • Please so us what you have so far and explain any condition such as what should happen when a range is outside of the start-end. Or if ranges are always in order. – Remy Kabel Jun 13 '17 at 09:37

2 Answers2

1

We can solve this by going over each range and pushing the intermediate ranges to the result array. The solution below does allow for the ranges to be unsorted, however, the exempted ranges are not allowed to:

  • Have overlap
  • (now fixed in code) Start at the start of the whole range (e.g. no exempted range may start at 0)
  • End at the end of the whole range (e.g. no exempted range may end at 100)
  • Have any start or end values outside of the whole range.

To account for these conditions you'd have to expand upon my code. If you do not know how to, let me know and I'll help!

var start = 0;
    var end = 100;
    var ranges = [
     { start: 0, end: 5 },
     { start: 25, end: 50 },
     { start: 60, end: 70 }
    ]

    // First sort the ranges based on the start
    var sortedRanges = ranges.sort(function(a,b) {
     return a.start - b.start;
    });

    var res = [];
    // Push each of the intermediate ranges to the result array
    for (var i = 0; i < ranges.length; i++) {
      if (ranges[i].start == start) {
        start = ranges[i].end+1;
        continue;
      }
      res.push({
        start: start,
        end: ranges[i].start - 1
      });
      start = ranges[i].end+1;
    }

    // Push the final range to the resultArray
    res.push({start: start, end: end});

    console.log(res);
Remy Kabel
  • 946
  • 1
  • 7
  • 15
  • thanks for this i have tried this... however it will not work if the range.start has 0... i am checking for simplifying code. – Akbar Basha Jun 13 '17 at 10:15
  • Next time when you question on StackOverflow, please explicitly note what you have already tried and exactly what you are facing difficulties with. Nevertheless, I have changed the code to include a check for the range starting at 0. – Remy Kabel Jun 13 '17 at 10:24
-1

It's simple code:

ranges.filter(function(item){return item.start>=start && item.end<=end})

guest
  • 706
  • 7
  • 15
  • This will only work if all ranges are in the array `ranges` to begin with. Unlike what the question is, where a full range is given together with the sub-ranges that should be exempted from this full range. – Remy Kabel Jun 13 '17 at 09:39