gabzim / circle-to-polygon

Receives a Coordinate, a Radius and a Number of edges and aproximates a circle by creating a polygon that fills its area
ISC License
113 stars 29 forks source link

Extend `numberOfEdges` to accept a callback #52

Open brandonmcconnell opened 11 months ago

brandonmcconnell commented 11 months ago

It would be very useful if the numberOfEdges option could accept a callback which would calculate the number of edges based on the size/radius/circumference of the circle.

The new usage might look something like this:

const circleToPolygon = require("circle-to-polygon");

const coordinates = [-27.4575887, -58.99029];
const radius = 100;
const numberOfEdges = ({ c }) => c / 4;

let polygon = circleToPolygon(coordinates, radius, { numberOfEdges });

And the definition for getNumberOfEdges could be adjusted to this:

const DEFAULT_NUMBER_OF_EDGES = 32;

function getNumberOfEdges(radius, options) {
  if (!options) return DEFAULT_NUMBER_OF_EDGES;
  if (!isObjectNotArray(options)) return options;

  if (typeof options.numberOfEdges === "function") {
    const circumference = 2 * Math.PI * radius;
    const numberOfEdges = options.numberOfEdges({ c: circumference, r: radius });
    if (Number.isFinite(numberOfEdges)) return Math.round(numberOfEdges);
    return DEFAULT_NUMBER_OF_EDGES;
  }

  return options.numberOfEdges ?? DEFAULT_NUMBER_OF_EDGES;
}