Validating a square in a 2-D plane in JavaScript


We are required to write a JavaScript function that takes in four arguments. The four arguments will all be arrays of exactly two numbers representing the coordinates of four vertices of a quadrilateral or any figure (closed or unclosed) on a plane.

The task of our function is to determine whether or not the four vertices form a square.

If they do form a square, we should return true, false otherwise.

For example −

If the input coordinates are −

const c1 = [1, 0];
const c2 = [-1, 0];
const c3 = [0, 1];
const c4 = [0, -1];

Then the output should be −

const output = true;

because these coordinates do form a square of area 4 unit sq.

Example

The code for this will be −

 Live Demo

const c1 = [1, 0];
const c2 = [-1, 0];
const c3 = [0, 1];
const c4 = [0, -1];
const validSquare = (c1, c2, c3, c4) => {
   const dist = (c1, c2) => (Math.sqrt(Math.pow(c1[0] - c2[0],2) + Math.pow(c1[1] - c2[1],2)));
   const points = [c1,c2,c3,c4];
   let lens = new Set();
   for(let i = 0; i < points.length; i++){
      for(let j = i + 1; j < points.length; j++){
         if(points[i][0] == points[j][0] && points[i][1] == points[j][1]){
            return false;
         };
         let dis = dist(points[i],points[j]);
         lens.add(dis)
      };
   };
   return lens.size === 2;
};
console.log(validSquare(c1, c2, c3, c4));

Output

And the output in the console will be −

true

Updated on: 26-Feb-2021

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements