SkillGG
SkillGG

Reputation: 686

How to check if two 'lines' overlap?

I know, its a dumb question, but I need to check if two periods of time (in epoch) overlap with each other. I just don't know if those checks will be sufficient.

TLPeriod.prototype.isOverlapping = function(period) {
    if( period.toPoints().start.getEpoch() < this.toPoints().start.getEpoch()
        &&
        this.toPoints().start.getEpoch() < period.toPoints().end.getEpoch())
        return true;
    if(this.toPoints().end.getEpoch() > period.toPoints().start.getEpoch())
        return true;
    return false;
};

I know, i should write here, but it would take lots of time to get an answer.

It could be quickly summarized to:

Two lines on the same axis with points:

|(this.start),(this.end)|

&

|(period.start),(period.end)|

How to check if they overlap?

OVERLAP!
|-----------|-----------------|-------------|
this.start  period.start     this.end     period.end

NO OVERLAP!
|-----------|              |-------------|
this.start  this.end     period.start  period.end

OVERLAP!
|-----------------|--------|-------------|
period.start  this.start  this.end     period.end

Upvotes: 0

Views: 131

Answers (1)

mbojko
mbojko

Reputation: 14679

An opposite question: when do they not overlap? The answer: when the first one starts after the second one ends, or when the second one starts after the first one ends. So

TLPeriod.prototype.isOverlapping = function(period) {
   return !(
      period.toPoints().start.getEpoch() > this.toPoints().end.getEpoch() ||
      this.toPoints().start.getEpoch() > period.toPoints().end.getEpoch()
   );
}

Upvotes: 1

Related Questions