- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- Finding distance between two points in a 2-D plane using JavaScript
- Validating brackets in a string in JavaScript
- Validating a power JavaScript
- Validating a password using JavaScript
- Validating a file size in JavaScript while uploading
- Validating a boggle word using JavaScript
- Validating a string with numbers present in it in JavaScript
- Find mirror image of a point in 2-D plane in C++
- Validating push pop sequence in JavaScript
- Validating alternating vowels and consonants in JavaScript
- Rotating a 2-D (transposing a matrix) in JavaScript
- Validating email and password - JavaScript
- Searching in a sorted 2-D array in JavaScript
- Validating a Form with Parsley.js
- Sorting only columns of a 2-D array in JavaScript

Advertisements