DutchKev DutchKev - 2 months ago 18
Node.js Question

Find 'holes' (gaps) in array of date ranges

Given you have an array of date ranges

var arr = [
{
"from": 'unix 1st of august',
"until": 'unix 5th of august'
},
{
"from": 'unix 15th of august',
"until": 'unix 20th of august'
},
{
"from": 'unix 25th of august',
"until": 'unix 31th of august'
}
];


What would be the easiest way to find 'holes' in the time ranges? in this case the 5th until the 15th and the 20th until the 25th is missing.

function findDateRangeHoles() {
let chunks = [];

arr.forEach(range => {
// ??
chunks.push({from: '?', until: '?'});
});

// Return value example, array of object, each holding a missing date range chunk
[
{
from: 'unix 5th of august',
until: 'unix 15th of august'
},
{
from: 'unix 20th of august',
until: 'unix 25th of august'
}
]

return chunks;
}

let missingChunks = findDateRangeHoles(1st of August, 31 of August); // Array of objects


Wonder if momentjs has something for it??

Answer

Here's an example, but in the future, you should post a real attempt, what you have posted does not show that you have tried it.

Sort them and compare the end of range a with the beginning of range b, as numbers. After you do that, convert the from and untils that you have created into date ranges

// Assuming they are sorted
var ranges = [{
  from: 946702800, // +new Date(2000, 0, 1) / 1000
  until: 949381200 // +new Date(2000, 1, 1)
},{
  from: 954565200,
  until: 957153600
},{
  from: 962424000,
  until: 965102400
}];

var holes = [];

for (var i=1; i < ranges.length; i++) {
  var beginningOfHole = ranges[i-1].until;
  var endOfHole = ranges[i].from;
  if (beginningOfHole < endOfHole) {
    holes.push({from: beginningOfHole + 1, until: endOfHole - 1});
  }
}

console.log('holes in ranges', holes.map(hole => ({
    from: new Date(hole.from * 1000), // Convert unix timestamp into JS timestamp
    until: new Date(hole.until * 1000)
})));