Skip to content

Commit

Permalink
New module @turf/clean-coords (#875)
Browse files Browse the repository at this point in the history
* created base module structure

* first implementation

* added tests, updated other files

* added yarn, updated README

* Add cleaning of MultiPoint

* Update JSDocs

* Update JSDocs

* Update JSDocs

* Update Typescript definition

* Update bench results

* Fix linting issues

* replaced for loops with forEach

* Added extra tests

* Remove clone

* Add helpers

* Add mutate param (include benchmark results)
  • Loading branch information
stebogit authored and DenisCarriere committed Aug 1, 2017
1 parent 22c04ff commit adb56ea
Show file tree
Hide file tree
Showing 27 changed files with 1,545 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/turf-clean-coords/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2017 TurfJS

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
50 changes: 50 additions & 0 deletions packages/turf-clean-coords/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# @turf/clean-coords

# cleanCoords

Removes redundant coordinates from any GeoJSON Geometry.

**Parameters**

- `geojson` **([Geometry](http://geojson.org/geojson-spec.html#geometry) \| [Feature](http://geojson.org/geojson-spec.html#feature-objects))** Feature or Geometry
- `mutate` **\[[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)]** allows GeoJSON input to be mutated (optional, default `false`)

**Examples**

```javascript
var line = turf.lineString([[0, 0], [0, 2], [0, 5], [0, 8], [0, 8], [0, 10]]);
var multiPoint = turf.multiPoint([[0, 0], [0, 0], [2, 2]]);

turf.cleanCoords(line).geometry.coordinates;
//= [[0, 0], [0, 10]]

turf.cleanCoords(multiPoint).geometry.coordinates;
//= [[0, 0], [2, 2]]
```

Returns **([Geometry](http://geojson.org/geojson-spec.html#geometry) \| [Feature](http://geojson.org/geojson-spec.html#feature-objects))** the cleaned input Feature/Geometry

<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source file (likely index.js), and re-run
./scripts/generate-readmes in the turf project. -->

---

This module is part of the [Turfjs project](http://turfjs.org/), an open source
module collection dedicated to geographic algorithms. It is maintained in the
[Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create
PRs and issues.

### Installation

Install this module individually:

```sh
$ npm install @turf/clean-coords
```

Or install the Turf module that includes it as a function:

```sh
$ npm install @turf/turf
```
77 changes: 77 additions & 0 deletions packages/turf-clean-coords/bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
const path = require('path');
const glob = require('glob');
const load = require('load-json-file');
const Benchmark = require('benchmark');
const cleanCoords = require('./');

/**
* Benchmark Results
*
* geometry: 0.675ms
* multiline: 0.044ms
* multipoint: 0.291ms
* multipolygon: 0.062ms
* point: 0.010ms
* polygon-with-hole: 0.017ms
* polygon: 0.010ms
* simple-line: 0.008ms
* triangle: 0.020ms
*
* // mutate=false (using geometry/feature)
* geometry x 1,524,640 ops/sec ±4.60% (74 runs sampled)
* multiline x 1,511,608 ops/sec ±8.79% (72 runs sampled)
* multipoint x 382,429 ops/sec ±3.56% (84 runs sampled)
* multipolygon x 808,277 ops/sec ±2.84% (82 runs sampled)
* point x 14,675,464 ops/sec ±4.42% (80 runs sampled)
* polygon-with-hole x 1,493,507 ops/sec ±5.53% (72 runs sampled)
* polygon x 2,386,278 ops/sec ±1.27% (86 runs sampled)
* simple-line x 4,195,499 ops/sec ±2.88% (86 runs sampled)
* triangle x 2,254,753 ops/sec ±1.10% (88 runs sampled)
*
* // mutate=false (using @turf/clone)
* geometry x 202,410 ops/sec ±1.43% (88 runs sampled)
* multiline x 235,421 ops/sec ±3.48% (86 runs sampled)
* multipoint x 280,757 ops/sec ±1.59% (87 runs sampled)
* multipolygon x 127,353 ops/sec ±1.35% (88 runs sampled)
* point x 18,233,987 ops/sec ±1.34% (86 runs sampled)
* polygon-with-hole x 199,203 ops/sec ±2.61% (84 runs sampled)
* polygon x 355,616 ops/sec ±1.58% (86 runs sampled)
* simple-line x 515,430 ops/sec ±2.40% (83 runs sampled)
* triangle x 286,315 ops/sec ±1.64% (86 runs sampled)
*
* // mutate=false (using JSON.parse + JSON.stringify)
* geometry x 93,681 ops/sec ±7.66% (75 runs sampled)
* multiline x 112,836 ops/sec ±4.60% (82 runs sampled)
* multipoint x 113,937 ops/sec ±1.09% (90 runs sampled)
* multipolygon x 71,131 ops/sec ±1.32% (90 runs sampled)
* point x 18,181,612 ops/sec ±1.36% (91 runs sampled)
* polygon-with-hole x 100,011 ops/sec ±1.14% (85 runs sampled)
* polygon x 154,331 ops/sec ±1.31% (89 runs sampled)
* simple-line x 193,304 ops/sec ±1.33% (90 runs sampled)
* triangle x 130,921 ops/sec ±3.37% (87 runs sampled)
*
* // mutate=true
* geometry x 2,016,365 ops/sec ±1.83% (85 runs sampled)
* multiline x 2,266,787 ops/sec ±3.69% (79 runs sampled)
* multipoint x 411,246 ops/sec ±0.81% (89 runs sampled)
* multipolygon x 1,011,846 ops/sec ±1.34% (85 runs sampled)
* point x 17,635,961 ops/sec ±1.47% (89 runs sampled)
* polygon-with-hole x 2,110,166 ops/sec ±1.59% (89 runs sampled)
* polygon x 2,887,298 ops/sec ±1.75% (86 runs sampled)
* simple-line x 7,109,682 ops/sec ±1.52% (87 runs sampled)
* triangle x 3,116,940 ops/sec ±0.71% (87 runs sampled)
*/
const suite = new Benchmark.Suite('turf-clean-coords');
glob.sync(path.join(__dirname, 'test', 'in', '*.geojson')).forEach(filepath => {
const {name} = path.parse(filepath);
const geojson = load.sync(filepath);
console.time(name);
cleanCoords(geojson);
console.timeEnd(name);
suite.add(name, () => cleanCoords(geojson, true));
});

suite
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
11 changes: 11 additions & 0 deletions packages/turf-clean-coords/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/// <reference types="geojson" />

type GeometryObject = GeoJSON.GeometryObject;
type Feature = GeoJSON.Feature<any>;

/**
* http://turfjs.org/docs/#cleancoords
*/
declare function cleanCoords<T extends GeometryObject|Feature>(feature: T, mutate?: boolean): T;
declare namespace cleanCoords {}
export = cleanCoords;
166 changes: 166 additions & 0 deletions packages/turf-clean-coords/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
var helpers = require('@turf/helpers');
var invariant = require('@turf/invariant');
var getCoords = invariant.getCoords;
var getGeomType = invariant.getGeomType;

/**
* Removes redundant coordinates from any GeoJSON Geometry.
*
* @name cleanCoords
* @param {Geometry|Feature} geojson Feature or Geometry
* @param {boolean} [mutate=false] allows GeoJSON input to be mutated
* @returns {Geometry|Feature} the cleaned input Feature/Geometry
* @example
* var line = turf.lineString([[0, 0], [0, 2], [0, 5], [0, 8], [0, 8], [0, 10]]);
* var multiPoint = turf.multiPoint([[0, 0], [0, 0], [2, 2]]);
*
* turf.cleanCoords(line).geometry.coordinates;
* //= [[0, 0], [0, 10]]
*
* turf.cleanCoords(multiPoint).geometry.coordinates;
* //= [[0, 0], [2, 2]]
*/
module.exports = function (geojson, mutate) {
if (!geojson) throw new Error('geojson is required');
var type = getGeomType(geojson);
var coords = getCoords(geojson);

// Store new "clean" points in this Array
var newCoords = [];

switch (type) {
case 'LineString':
newCoords = cleanCoords(geojson);
break;
case 'MultiLineString':
case 'Polygon':
coords.forEach(function (line) {
newCoords.push(cleanCoords(line));
});
break;
case 'MultiPolygon':
coords.forEach(function (polygons) {
var polyPoints = [];
polygons.forEach(function (ring) {
polyPoints.push(cleanCoords(ring));
});
newCoords.push(polyPoints);
});
break;
case 'Point':
return geojson;
case 'MultiPoint':
var existing = {};
coords.forEach(function (coord) {
var key = coord.join('-');
if (!existing.hasOwnProperty(key)) {
newCoords.push(coord);
existing[key] = true;
}
});
break;
default:
throw new Error(type + ' geometry not supported');
}

// Support input mutation
if (geojson.coordinates) {
if (mutate === true) {
geojson.coordinates = newCoords;
return geojson;
}
return geometry(geojson, type, newCoords);
} else {
if (mutate === true) {
geojson.geometry.coordinates = newCoords;
return geojson;
}
return feature(geojson, type, newCoords);
}
};

/**
* Create Geometry from existing Geometry
*
* @param {Geometry} geojson Existing Geometry
* @param {string} type Geometry Type
* @param {Array<number>} coordinates Coordinates
* @returns {Geometry} Geometry
*/
function geometry(geojson, type, coordinates) {
var geom = {
type: type,
coordinates: coordinates
};
if (geojson.bbox) geom.bbox = geojson.bbox;
return geom;
}

/**
* Create Feature from existing Feature
*
* @param {Feature} geojson Existing Feature
* @param {string} type Feature Type
* @param {Array<number>} coordinates Coordinates
* @returns {Feature} Feature
*/
function feature(geojson, type, coordinates) {
var feat = helpers.feature(geometry(geojson.geometry, type, coordinates), geojson.properties);
if (geojson.id) feat.id = geojson.id;
if (geojson.bbox) feat.bbox = geojson.bbox;
return feat;
}

/**
* Clean Coords
*
* @private
* @param {Array<number>|LineString} line Line
* @returns {Array<number>} Cleaned coordinates
*/
function cleanCoords(line) {
var points = getCoords(line);

var prevPoint, point, nextPoint;
var newPoints = [];
var secondToLast = points.length - 1;

newPoints.push(points[0]);
for (var i = 1; i < secondToLast; i++) {
prevPoint = points[i - 1];
point = points[i];
nextPoint = points[i + 1];

if (!isPointOnLineSegment(prevPoint, nextPoint, point)) {
newPoints.push(point);
}
}
newPoints.push(nextPoint);
return newPoints;
}

/**
* Returns if `point` is on the segment between `start` and `end`.
* Borrowed from `@turf/boolean-point-on-line` to speed up the evaluation (instead of using the module as dependency)
*
* @private
* @param {Array<number>} start coord pair of start of line
* @param {Array<number>} end coord pair of end of line
* @param {Array<number>} point coord pair of point to check
* @returns {boolean} true/false
*/
function isPointOnLineSegment(start, end, point) {
var x = point[0], y = point[1];
var startX = start[0], startY = start[1];
var endX = end[0], endY = end[1];

var dxc = x - startX;
var dyc = y - startY;
var dxl = endX - startX;
var dyl = endY - startY;
var cross = dxc * dyl - dyc * dxl;

if (cross !== 0) return false;
else if (Math.abs(dxl) >= Math.abs(dyl)) return dxl > 0 ? startX <= x && x <= endX : endX <= x && x <= startX;
else return dyl > 0 ? startY <= y && y <= endY : endY <= y && y <= startY;
}
44 changes: 44 additions & 0 deletions packages/turf-clean-coords/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "@turf/clean-coords",
"version": "4.5.0",
"description": "turf clean-coords module",
"main": "index.js",
"types": "index.d.ts",
"files": [
"index.js",
"index.d.ts"
],
"scripts": {
"test": "node test.js",
"bench": "node bench.js"
},
"repository": {
"type": "git",
"url": "git://github.com/Turfjs/turf.git"
},
"keywords": [
"turf",
"gis",
"clean-coords"
],
"author": "Turf Authors",
"contributors": [
"Stefano Borghi <@stebogit>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/Turfjs/turf/issues"
},
"homepage": "https://github.com/Turfjs/turf",
"devDependencies": {
"@turf/truncate": "^4.5.2",
"benchmark": "^2.1.4",
"load-json-file": "^2.0.0",
"tape": "^4.6.3",
"write-json-file": "^2.2.0"
},
"dependencies": {
"@turf/helpers": "^4.5.2",
"@turf/invariant": "^4.5.2"
}
}
Loading

0 comments on commit adb56ea

Please sign in to comment.