Skip to content

Commit

Permalink
Merge pull request #2 from siebenschlaefer/included_line_segments
Browse files Browse the repository at this point in the history
fixed handling of collinear, included lines
  • Loading branch information
pgkelley4 committed Apr 3, 2016
2 parents c50d465 + 39d4425 commit b6b2726
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
33 changes: 29 additions & 4 deletions js/line-segments-intersect.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,16 @@ function doLineSegmentsIntersect(p, p2, q, q2) {
return true
}
// Do they overlap? (Are all the point differences in either direction the same sign)
// Using != as exclusive or
return ((q.x - p.x < 0) != (q.x - p2.x < 0) != (q2.x - p.x < 0) != (q2.x - p2.x < 0)) ||
((q.y - p.y < 0) != (q.y - p2.y < 0) != (q2.y - p.y < 0) != (q2.y - p2.y < 0));
return !allEqual(
(q.x - p.x < 0),
(q.x - p2.x < 0),
(q2.x - p.x < 0),
(q2.x - p2.x < 0)) ||
!allEqual(
(q.y - p.y < 0),
(q.y - p2.y < 0),
(q2.y - p.y < 0),
(q2.y - p2.y < 0));
}

if (denominator == 0) {
Expand Down Expand Up @@ -86,4 +93,22 @@ function subtractPoints(point1, point2) {
*/
function equalPoints(point1, point2) {
return (point1.x == point2.x) && (point1.y == point2.y)
}
}

/**
* See if all arguments are equal.
*
* @param {...} args arguments that will be compared by '=='.
*
* @return if all arguments are equal
*/
function allEqual(args) {
var firstValue = arguments[0],
i;
for (i = 1; i < arguments.length; i += 1) {
if (arguments[i] != firstValue) {
return false;
}
}
return true;
}
8 changes: 8 additions & 0 deletions js/test-line-segments-intersect.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,11 @@ test( "Collinear with overlap with negatives", function() {
q2 = {x:0, y:-4};
equal( doLineSegmentsIntersect(p, p2, q, q2), true, "Passed!" );
});

test( "Collinear, q is part of p", function() {
p = {x:10, y:0};
p2 = {x:40, y:0};
q = {x:30, y:0};
q2 = {x:20, y:0};
equal( doLineSegmentsIntersect(p, p2, q, q2), true, "Passed!" );
});

0 comments on commit b6b2726

Please sign in to comment.