find the area of a regular polygon in javascript

To find the area of a regular polygon in JavaScript, we can use the following formula:

index.tsx
area = (0.25 * n * s^2) / (tan(π/n))
37 chars
2 lines

where n is the number of sides and s is the length of each side.

Here's the JavaScript function:

index.tsx
function getPolygonArea(n, s) {
  const radians = Math.PI / n;
  const tan = Math.tan(radians);
  const numerator = 0.25 * n * s ** 2;
  const denominator = tan;
  const area = numerator / denominator;
  return area;
}
219 chars
9 lines

We can then call this function with the number of sides and the length of each side to get the area:

index.tsx
const area = getPolygonArea(6, 10);
console.log(area); // Output: 259.8076211353316
84 chars
3 lines

gistlibby LogSnag