-1

I have a range that is defined by start and end, and an array of ranges in collection

var start = 10;
var end = 60;

var collection = [
    {start:5, end:15},
    {start:15, end:30},
    {start:45, end:60}
];

How to check if ranges in collection are within start and end and covered the whole range?

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Gooch
  • 39
  • 6
  • 3
    Have you tried anything to solve this problem? Looping over the collection seems like a good start. – Yannick K May 28 '20 at 16:14
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and use the available [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) methods. – Sebastian Simon May 28 '20 at 16:26
  • 1
    You can use any loops or you can use `filter` like this: `const newCollection = collection.filter(c=>c.start>=start && c.end <= end)` – Denis Stukalov May 28 '20 at 16:30

1 Answers1

0

I found the solution by :

  • Expanding the main range into array of numbers.
  • Loop collection, expand also those into array of numbers.
  • Check if the array is within the range, if it's within range remove those numbers from the main array, if not return false (array to check is not witin range)
  • After the loop, check the length of main array, if it's more than 0 return false (array collection is within range, but doesn't cover the main range). If it's 0 meaning the collection array is within range, and cover the whole main array.

When googling I found the use of lodash. here is the code in my function :

let parentRange = _.range(start, end + 1); // Expand into array of numbers

for (var i = 0; i < collection.length; i++) {
    let rangeToCheck = _.range(collection[i].start, collection[i].end + 1); //Also expand into array of numbers
    if (_.difference(rangeToCheck, parentRange).length === 0) { // Check if collection range is within parent range
        _.pullAll(parentRange, rangeToCheck); // Remove the numbers from parent range that matches collcection range
    } else {
        return false; // Not within parent range
    }
}

// Check if parent range has values left
if (parentRange.length != 0) {
    return false; // Collection ranges does not cover parent range
} else {
    return true; // Collection ranges is within parent range, and cover the whole numbers
}
Gooch
  • 39
  • 6