hasVertiсalSym
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.4.1/chai.js"></script>
<div id="mocha"></div>
JavaScript
function hasVertiсalSym(points) {
const pointsSortedByX = [...points].sort((a, b) => b.x > a.x ? 1 : -1); // 2, 3, 6, 999
for(let i = 0; i <= pointsSortedByX.length / 2; i++) {
const left = pointsSortedByX[i]; // 3
const right = pointsSortedByX[pointsSortedByX.length - i - 1]; // 6
if(left.y !== right.y) return false; // ok
const evenLefter = pointsSortedByX[i - 1]; // 2
const eventRighter = pointsSortedByX[pointsSortedByX.length - i]; // 999
if(typeof evenLefter !== 'undefined' && typeof eventRighter !== 'undefined') {
const dxLeft = left.x - evenLefter.x; // 1
const dxRight = evenRighter.x - right.x; // 993
if(dxLeft !== dxRight) return false;
}
}
return true;
}
// ТЕСТЫ
mocha.setup('bdd');
var expect = chai.expect;
[
[[], true],
[[{x:1,y:1}], true],
[[{x:1,y:1},{x:1,y:1}], true],
[[{x:3,y:2},{x:5,y:2}], true],
[[{x:1,y:1},{x:1,y:1},{x:3,y:2},{x:5,y:2}], false], // 2 точки на одной гориз. оси, 2 на другой
[[{x:3,y:2},{x:4,y:1}], false], // 2 точки на разных осях
[[{x:2,y:0},{x:6,y:0},{x:3,y:0},{x:5,y:0}], true], // 4 точки на одной оси
[[{x:2,y:0},{x:6,y:0},{x:3,y:0},{x:999,y:0}], false], // 4 точки на одной оси
].forEach(([points, result]) => it(JSON.stringify([points, result]), () => {
expect(hasVertiсalSym(points)).equal(result);
}));
mocha.run();