Skip to content

Instantly share code, notes, and snippets.

@tnraro
Last active July 12, 2021 15:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tnraro/f6c0bf3daa711721d3ce0dea1c37124a to your computer and use it in GitHub Desktop.
Save tnraro/f6c0bf3daa711721d3ce0dea1c37124a to your computer and use it in GitHub Desktop.
determine the area of a polygon. using shoelace formula algorithm.
Math.area = Math.area || function(polygon){
const length = polygon.length;
let sum = 0;
for(let i = 0; i < length; i += 2){
sum += polygon[i ] * polygon[(i + 3) % length]
- polygon[i + 1] * polygon[(i + 2) % length];
}
return Math.abs(sum) * 0.5;
}
Math.area([
0, 0,
3, 0,
0, 4
]); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment