JSFiddle - React, Tailwind, and code Playground

by blesh

JavaScript

//fiddling with intersections.
var poly1 = new Polygon([0, 0], [1, 1], [1, 0]);
var poly2 = new Polygon([5, 5], [6, 6], [6, 5]);

console.log(polyIntersection(poly1, poly2));

function forEach(coll, fn) {
    for (var i = 0; i < coll.length; i++) {
        fn(coll[i], i);
    }
}

function Polygon() {
    var pts = []
    if (isArray(arguments[0])) {
        forEach(arguments, function (pt) {
            pts.push(new Point(pt));
        });
    } else {
        pts = arguments.slice();
    }
    this.points = pts;

    var index = 0;
    this.nextSegment = function () {
        if (index > pts.length + 1) return null;
        var a = index++ % pts.length,
            b = index++ % pts.length;
        return new Line(pts[a], pts[b]);
    }
}

function polyIntersection(poly1, poly2) {
    var seg;
    while(seg = poly1.nextSegment()) {
        if(polyLineIntersection(poly2, seg)) {
            return true;
        }
    }
    return false;
}

function polyLineIntersection(poly, line) {
    var seg;
    while(seg = poly.nextSegment()) {
        if (segmentsIntersect(seg, line)) {
            return true;
        }
    }
    return false;
}

function getIntersection(line1, line2) {
    var x, y, m, b;
    if (line1.slope === line2.slope) {
        return new Point([NaN, NaN]);
    }
    if (line1.slope === Infinity) {
        x = line1.pt1.x;
        m = line2.slope;
        b = line2.b;
    } else {
        if (line2.slope === Infinity) {
            x = line2.pt1.x;
        } else {
            x = (line2.b - line1.b) / (line1.slope - line2.slope);
        }
        m = line1.slope;
        b = line1.b;
    }
    y = (m * x) + b;
    return new Point(x, y);
}

function segmentsIntersect(seg1, seg2) {
    var intPt = getIntersection(seg1, seg2);
    return intPt.x >= seg1.minX && intPt.x <= seg1.maxX && intPt.x >= seg2.minX && intPt.y <= seg2.maxX;
}

function Point(x, y) {
    if (isArray(x)) {
        this.x = x[0];
        this.y = x[1];
    } else {
       ...