JSFiddle - React, Tailwind, and code Playground
JavaScript
var poly1 = [{x:0, y:0}, {x:0, y:1}, {x:1, y:1}, {x:1, y:0}]; // square
var poly2 = [{x:0, y:0}, {x:0, y:1}, {x:1, y:1}, {x:2, y:0}]; // long side
var poly3 = [{x:0, y:0}, {x:0, y:1}, {x:1, y:2}, {x:1, y:0}]; // long diag
var poly4 = [{x:0, y:0}, {x:0, y:1}, {x:1, y:-1}, {x:1, y:0}]; // rotated diag
if (confirm("Run Program?")) {
Run("poly1", poly1);
Run("poly2", poly2);
Run("poly3", poly3);
Run("poly4", poly4);
}
function Run(name, poly) {
var total = 0;
for (var i = 0; i < 4; i++) {
total += Test(i, poly);
}
if (total === 4) {
alert(name + " is a square");
}
else { alert(name + " is not a square"); }
}
function Test(i, poly) {
var org = poly[i];
poly.splice(i, 1);
poly.splice(0, 0, org);
var dist = GetAllDistSquared(poly);
var max = Math.max.apply(Math, dist);
var min = Math.min.apply(Math, dist);
var comp = Math.abs(dist[0] - dist[1] - dist[2]);
if (comp === max && max != min && 2 * min === max) {
return 1;
}
else { return 0; }
}
function GetAllDistSquared(poly) {
var d1 = GetDistSquared(poly[0], poly[1]);
var d2 = GetDistSquared(poly[0], poly[2]);
var d3 = GetDistSquared(poly[0], poly[3]);
return [d1, d2, d3];
}
function GetDistSquared(p1, p2) {
var dx = p1.x - p2.x;
var dy = p1.y - p2.y;
return dx * dx + dy * dy;
}