Mathias Dewelde
Mathias Dewelde

Reputation: 705

Test in which ranges the collection of dates aren't overlapping

I wrote a script to render a timeline with a dataset in javascript. But i have to mark the area's where no info is found (yellow in the image). I absolutely have no idea how to get the ranges without info in the dataset. (i use momentjs for date calculations)

Example dataset:

data: [
    {id: 1, lane: 1, start: 05-02-2006, end: 09-09-2008},
    {id: 2, lane: 2, start: 01-01-2008, end: 31-07-2010},
    {id: 3, lane: 3, start: 15-12-2013, end: 12-02-2016}
]

Example image: enter image description here

Upvotes: 1

Views: 41

Answers (1)

adeneo
adeneo

Reputation: 318182

I would create an new array and fill in the voids, something like this

var dates = [];

for (var i=0; i<data.length; i++) {
    var now       = data[i],
        thisStart = parseDate(now.start),
        thisEnd   = parseDate(now.end),
        prevEnd   = data[i-1] ? parseDate(data[i-1].end) : null;

    if ( prevEnd && prevEnd <= thisStart ) {
        dates.push({id: i + 0.5, lane: 0, start: prevEnd, end: thisStart});
    }

    dates.push({id : now.id, lane: now.lane, start: thisStart, end: thisEnd});
}

and you'll end up with an array like this

dates : [
    {id: 1, lane: 1, start: "2006-02-04T23:00:00.000Z", end: "2008-09-08T22:00:00.000Z"},
    {id: 2, lane: 2, start: "2007-12-31T23:00:00.000Z", end: "2010-07-30T22:00:00.000Z"},
    {id: 2.5, lane: 0, start: "2010-07-30T22:00:00.000Z", end: "2013-12-14T23:00:00.000Z"},
    {id: 3, lane: 3, start: "2013-12-14T23:00:00.000Z", end: "2016-02-11T23:00:00.000Z"}
]

Note that I marked the object that fills the voids with an id if .5 and lane 0, you could do whatever you wanted there, as long as it's recognizable to you when you create the layout.

I also created a parseDate function, all it does is parse the dates for you to valid date objects, it's included in the fiddle below

FIDDLE

Upvotes: 1

Related Questions