Erik
Erik

Reputation: 14770

How to check intersection of dates in backbone collection?

I have Backbone collection that consists of models that have the following attributes:

{
  startTime: Date('...'),
  endTime: Date('...')
}

When I add a new model I have to check that there is no dates intersections between added and exists ones.

So for example:

var startTime = new Date();
var endTime = new Date(new Date().setHours(1));

if (!this.collection.check({startTime: startTime, endTime })) {
   this.create({startTime: startTime, endTime });
} 

What's the best way to do this?

Upvotes: 1

Views: 518

Answers (1)

nikoshr
nikoshr

Reputation: 33364

You could test every model in your collection to check if the future dates do not overlap with an existing interval. For example, and with a condition based on the answers in JavaScript date range between date range,

var C = Backbone.Collection.extend({
    check: function(opts) {
       // returns true if the given interval overlaps with any model
        var start = opts.startTime,
            end = opts.endTime;

        return this.any(function(model) {
            // returns true if the given interval overlaps
            return !((model.get('startTime')>=end) || (model.get('endTime')<=start));
        });
    }
});

And a demo http://jsfiddle.net/nikoshr/eaF5z/2/

Or if you prefer a more explicit version

var C = Backbone.Collection.extend({
    check: function(opts) {
        var startdate = opts.startTime,
            enddate = opts.endTime;

        return this.any(function(model) {
            var startD = model.get('startTime'),
                endD = model.get('endTime');

            return (startD >= startdate && startD <= enddate) || 
                    (startdate >= startD && startdate <= endD);
        });
    }
});

http://jsfiddle.net/nikoshr/duu3M/

Upvotes: 2

Related Questions