From f4a00b265dbb2f18266a78528d9a6ee3dd2389ba Mon Sep 17 00:00:00 2001 From: James Beard Date: Sat, 21 Sep 2024 21:16:07 +1000 Subject: [PATCH] Reversed the order in which random polygon points are generated to satisfy the right hand rule (#2715) Reversed the order in which random polygon points are generated to satisfy to the right hand rule for polygons. Added a simple benchmark test for turf-random. --- packages/turf-random/bench.ts | 21 +++++++++++---------- packages/turf-random/index.ts | 12 ++++++------ 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/packages/turf-random/bench.ts b/packages/turf-random/bench.ts index f5ddaa89db..64f3d440a0 100644 --- a/packages/turf-random/bench.ts +++ b/packages/turf-random/bench.ts @@ -1,15 +1,16 @@ -// I don't think this bench test does anything? There is no entry point into -// the module called random() that takes a string? +import Benchmark, { Event } from "benchmark"; +import { randomPolygon } from "./index.js"; -import { random } from "./index.js"; -import Benchmark from "benchmark"; +let totalTime = 0.0; +const suite = new Benchmark.Suite("turf-random"); -var suite = new Benchmark.Suite("turf-random"); suite - .add("turf-random", function () { - random("point"); - }) - .on("cycle", function (event) { - console.log(String(event.target)); + .add("turf-random", () => randomPolygon(1, { num_vertices: 100000 }), { + onComplete: (e: Event) => + (totalTime = totalTime += e.target.times?.elapsed), }) + .on("cycle", (e: Event) => console.log(String(e.target))) + .on("complete", () => + console.log(`completed in ${totalTime.toFixed(2)} seconds`) + ) .run(); diff --git a/packages/turf-random/index.ts b/packages/turf-random/index.ts index 257e26c0f4..a52fddae68 100644 --- a/packages/turf-random/index.ts +++ b/packages/turf-random/index.ts @@ -145,16 +145,16 @@ function randomPolygon( const features = []; for (let i = 0; i < count; i++) { - let vertices: any[] = []; + let vertices: number[][] = []; const circleOffsets = [...Array(options.num_vertices + 1)].map(Math.random); // Sum Offsets - circleOffsets.forEach((cur: any, index: number, arr: any[]) => { + circleOffsets.forEach((cur, index, arr) => { arr[index] = index > 0 ? cur + arr[index - 1] : cur; }); // scaleOffsets - circleOffsets.forEach((cur: any) => { + circleOffsets.forEach((cur) => { cur = (cur * 2 * Math.PI) / circleOffsets[circleOffsets.length - 1]; const radialScaler = Math.random(); vertices.push([ @@ -165,9 +165,9 @@ function randomPolygon( vertices[vertices.length - 1] = vertices[0]; // close the ring // center the polygon around something - vertices = vertices.map( - vertexToCoordinate(randomPositionUnchecked(paddedBbox)) - ); + vertices = vertices + .reverse() // Make counter-clockwise to adhere to right hand rule. + .map(vertexToCoordinate(randomPositionUnchecked(paddedBbox))); features.push(polygon([vertices])); } return featureCollection(features);