Skip to content

@turf/simplify gets stuck in an infinite loop on certain geometries #1788

@senritsu

Description

@senritsu

Under certain circumstances the turf/simplify function never terminates.

The issue appeared with a geometry resulting from a union of 2 adjacent geometries that left a small gap in between the original polygons.

Full geometry on geojson.io and the problematic ring by itself on geojson.io

This fiddle reproduces the issue using only the problematic ring itself, not the full geometry.

The freeze occurs in the commented part of this function here in simplify/index.js

function simplifyPolygon(coordinates, tolerance, highQuality) {
    return coordinates.map(function (ring) {
        var pts = ring.map(function (coord) {
            return {x: coord[0], y: coord[1]};
        });
        if (pts.length < 4) {
            throw new Error('invalid polygon');
        }
        var simpleRing = simplifyJS(pts, tolerance, highQuality).map(function (coords) {
            return [coords.x, coords.y];
        });
        //remove 1 percent of tolerance until enough points to make a triangle
        while (!checkValidity(simpleRing)) {
            tolerance -= tolerance * 0.01;
            simpleRing = simplifyJS(pts, tolerance, highQuality).map(function (coords) {
                return [coords.x, coords.y];
            });
        }
        if (
            (simpleRing[simpleRing.length - 1][0] !== simpleRing[0][0]) ||
            (simpleRing[simpleRing.length - 1][1] !== simpleRing[0][1])) {
            simpleRing.push(simpleRing[0]);
        }
        return simpleRing;
    });
}

For the given example geometry the simplifyJS call returns an invalid ring (with only 3 points: [[11.662180661499999, 50.1081498005], [11.662192661499999, 50.108041800500004], [11.662180661499999, 50.1081498005]]) no matter how small the tolerance gets. This means the loop never terminates, and the page hangs.

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions