Checking for convex polygon in JavaScript



Convex Polygon

A convex polygon is defined as a polygon with all its interior angles less than 180°.

Problem

We are required to write a JavaScript function that takes in an array of coordinates, basically the array will be an array of arrays each subarray containing exactly two numbers, specifying a point on a 2-D plane.

Our function should determine whether the polygon formed by these points is a convex polygon or not. If yes, the function should return true, false otherwise.

For example, if the input to the function is −

const arr = [[0,0],[0,1],[1,1],[1,0]];

Then the output should be −

const output = true;

Output Explanation:

These points will draw out a perfect square in which all the vertices have an interior angle of 90.

Example

The code for this will be −

 Live Demo

const arr = [[0,0],[0,1],[1,1],[1,0]]; const isConvex = (arr = []) => {    const { length } = arr;    let pre = 0, curr = 0;    for (let i = 0; i < length; ++i) {       let dx1 = arr[(i + 1) % length][0] - arr[i][0];       let dx2 = arr[(i + 2) % length][0] - arr[(i + 1) % length][0];       let dy1 = arr[(i + 1) % length][1] - arr[i][1];       let dy2 = arr[(i + 2) % length][1] - arr[(i + 1) % length][1];       curr = dx1 * dy2 - dx2 * dy1;       if (curr != 0) {          if ((curr > 0 && pre < 0) || (curr < 0 && pre > 0))             return false;          else             pre = curr;       };    };    return true; }; console.log(isConvex(arr));

Output

And the output in the console will be −

true
Updated on: 2021-03-04T11:38:16+05:30

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements