Skip to content

Instantly share code, notes, and snippets.

@gosoccerboy5
Last active May 10, 2022 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gosoccerboy5/0a16e3514fbadf8732e749e5b27dabfb to your computer and use it in GitHub Desktop.
Save gosoccerboy5/0a16e3514fbadf8732e749e5b27dabfb to your computer and use it in GitHub Desktop.
Find the perimeter or area of a polygon from a set of points
/**
* area(Array<Array<Number>> ...list)
*
* takes in a set of points (in clockwise or counterclockwise order) and returns the area of the polygon the points form
* example call: `area([3, 10], [9, 7], [11, 2], [2, 2]);`
**/
function area(...list) {
let total = 0;
for (let index = 0; index < list.length; index++) {
const point = list[index];
let nextPoint = list[index+1];
nextPoint ??= list[0];
total += (point[0] * nextPoint[1] - point[1] * nextPoint[0]);
}
return Math.round(Math.abs(total/2) * 100)/100;
}
area([3, 10], [9, 7], [11, 2], [2, 2]); // 48
/**
* perim(Array<Array<Number>> ...list)
*
* takes in a set of points (in clockwise or counterclockwise order) and returns the perimeter of the polygon it forms
* example call: `perim([-4, -2], [2, -5], [-4, -9]);`
**/
function perim(...list) {
let total = 0;
for (let index = 0; index < list.length; index++) {
const point = list[index];
let nextPoint = list[Number(index)+1];
nextPoint ??= list[0];
total += Math.sqrt((point[0]-nextPoint[0])**2 + (point[1]-nextPoint[1])**2);
}
return Math.round(total*100)/100;
}
perim([-4, -2], [2, -5], [-4, -9]); // 20.92
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment