green theoreom in javascript

Here's an implementation of the green theorem in JavaScript:

index.tsx
function greenTheorem(points) {
  const n = points.length;

  let area = 0;
  for (let i = 0; i < n; i++) {
    const j = (i + 1) % n;
    area += points[i].x * points[j].y - points[j].x * points[i].y;
  }
  area /= 2;

  let cx = 0, cy = 0;
  for (let i = 0; i < n; i++) {
    const j = (i + 1) % n;
    cx += (points[i].x + points[j].x) * (points[i].x * points[j].y - points[j].x * points[i].y);
    cy += (points[i].y + points[j].y) * (points[i].x * points[j].y - points[j].x * points[i].y);
  }
  cx /= (6 * area);
  cy /= (6 * area);

  return { area, centroid: { x: cx, y: cy } };
}
589 chars
22 lines

This function expects an array of points, where each point is an object with x and y properties, e.g.:

index.tsx
const points = [
  { x: 0, y: 0 },
  { x: 1, y: 0 },
  { x: 1, y: 1 },
  { x: 0, y: 1 },
];
const result = greenTheorem(points);
console.log(result);
// { area: 1, centroid: { x: 0.5, y: 0.5 } }
195 chars
10 lines

The greenTheorem function calculates the area and centroid of the polygon defined by the points using the green theorem. The area is calculated as the sum of the cross products of each pair of adjacent points divided by 2. The centroid is calculated using the formula:

$$ \frac{1}{6A}\sum_{i=0}^{n-1}(x_i+x_{i+1})(x_iy_{i+1}-x_{i+1}y_i), \frac{1}{6A}\sum_{i=0}^{n-1}(y_i+y_{i+1})(x_iy_{i+1}-x_{i+1}y_i) $$

where A is the area of the polygon.

Note that the points must be ordered either clockwise or counterclockwise for this to work correctly.

related categories

gistlibby LogSnag