Skip to content

Commit

Permalink
cellPolygons filter out empty cells and have the cell index as a prop…
Browse files Browse the repository at this point in the history
…erty

fixes #106

(Also fixes the test case, in which the clipped cell had 0 point but was not null, resulting in [undefined, undefined] values.)
  • Loading branch information
Fil committed May 28, 2020
1 parent 3be68e0 commit 6d0ffff
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ Renders the cell with the specified index *i* to the specified *context*. The sp

<a href="#voronoi_cellPolygons" name="voronoi_cellPolygons">#</a> <i>voronoi</i>.<b>cellPolygons</b>() [<>](https://github.com/d3/d3-delaunay/blob/master/src/voronoi.js "Source")

Returns an iterable over the [polygons for each cell](#voronoi_cellPolygon), in order.
Returns an iterable over the non-empty [polygons for each cell](#voronoi_cellPolygon), with the cell index as property.

<a href="#voronoi_cellPolygon" name="voronoi_cellPolygon">#</a> <i>voronoi</i>.<b>cellPolygon</b>(<i>i</i>) [<>](https://github.com/d3/d3-delaunay/blob/master/src/voronoi.js "Source")

Expand Down
4 changes: 2 additions & 2 deletions src/voronoi.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export default class Voronoi {
renderCell(i, context) {
const buffer = context == null ? context = new Path : undefined;
const points = this._clip(i);
if (points === null) return;
if (points === null || !points.length) return;
context.moveTo(points[0], points[1]);
let n = points.length;
while (points[0] === points[n-2] && points[1] === points[n-1] && n > 1) n -= 2;
Expand All @@ -122,7 +122,7 @@ export default class Voronoi {
const {delaunay: {points}} = this;
for (let i = 0, n = points.length / 2; i < n; ++i) {
const cell = this.cellPolygon(i);
if (cell) yield cell;
if (cell) cell.index = i, yield cell;
}
}
cellPolygon(i) {
Expand Down
9 changes: 9 additions & 0 deletions test/voronoi-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,12 @@ tape("a degenerate triangle is avoided", test => {
const voronoi = Delaunay.from(pts).voronoi([10, 10, 960, 500]);
test.equal(voronoi.cellPolygon(0).length, 4);
});

tape("cellPolygons filter out empty cells and have the cell index as a property", test => {
const pts = [[0, 0], [3, 3], [1, 1], [-3, -2]];
const voronoi = Delaunay.from(pts).voronoi([0, 0, 2, 2]);
test.deepEqual([...voronoi.cellPolygons()], [
Object.assign([[0, 0], [1, 0], [0, 1], [0, 0]], {index:0, }),
Object.assign([[0, 1], [1, 0], [2, 0], [2, 2], [0, 2], [0, 1]], { index: 2 })
]);
});

0 comments on commit 6d0ffff

Please sign in to comment.