我有一个由start
和end
定义的范围,以及一个collection
中的范围数组
var start = 10;
var end = 60;
var collection = [
{start:5, end:15},
{start:15, end:30},
{start:45, end:60}
];
如何检查collection
中的范围是否在start
和end
之内并且覆盖了整个范围?
答案 0 :(得分:0)
我通过以下方式找到了解决方案:
在谷歌搜索时,我发现使用了lodash。这是我函数中的代码:
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
}