find the area of a regular polygon in typescript

To find the area of a regular polygon in TypeScript, we'll need to use the formula:

Area = (1/2) * (number of sides) * (length of side) * (apothem)

Where the apothem is the distance from the center of the polygon to the midpoint of any side.

Here's a function that takes in the number of sides and length of side as parameters, and returns the area of the corresponding regular polygon.

index.ts
function findAreaOfRegularPolygon(numOfSides: number, lenOfSide: number): number {
  const apothem = lenOfSide / (2 * Math.tan(Math.PI / numOfSides));
  const area = (1 / 2) * numOfSides * lenOfSide * apothem;
  return area;
}
227 chars
6 lines

Here's an example usage of the function:

index.ts
const numOfSides = 6;
const lenOfSide = 5;
const area = findAreaOfRegularPolygon(numOfSides, lenOfSide);
console.log(`The area of the ${numOfSides}-sided regular polygon with side length ${lenOfSide} is ${area}.`);
215 chars
5 lines

This will output:

index.ts
The area of the 6-sided regular polygon with side length 5 is 64.9519052838329.
80 chars
2 lines

Note that the Math object and its trigonometric functions are used to calculate the apothem.

gistlibby LogSnag