-
Notifications
You must be signed in to change notification settings - Fork 944
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New module @turf/clean-coords
#875
Merged
Merged
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
195cadd
created base module structure
stebogit fcdda7b
first implementation
stebogit 8cdd1a3
added tests, updated other files
stebogit 79a9b57
added yarn, updated README
stebogit 93b2dd3
Merge branch 'master' into clean-coords
DenisCarriere 27103e2
Add cleaning of MultiPoint
DenisCarriere 69dd6b4
Update JSDocs
DenisCarriere 7b34a56
Update JSDocs
DenisCarriere 8c94d5f
Update JSDocs
DenisCarriere cc1f7a0
Update Typescript definition
DenisCarriere cf079ef
Update bench results
DenisCarriere ce1e3a7
Fix linting issues
DenisCarriere 45e8ab1
replaced for loops with forEach
stebogit 36ca0d1
Added extra tests
DenisCarriere d684814
Remove clone
DenisCarriere d4a296d
Add helpers
DenisCarriere 11f20ee
Add mutate param (include benchmark results)
DenisCarriere 54018e6
Merge branch 'master' into clean-coords
DenisCarriere b718b5c
Merge branch 'master' into clean-coords
DenisCarriere File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# @turf/clean-coords | ||
|
||
# cleanCoords | ||
|
||
Removes redundant coordinates from a (Multi)LineString or (Multi)Polygon; ignores (Multi)Point. | ||
|
||
**Parameters** | ||
|
||
- `geojson` **([Geometry](http://geojson.org/geojson-spec.html#geometry) \| [Feature](http://geojson.org/geojson-spec.html#feature-objects)<any>)** 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 = trf.lineString([[0, 0], [0, 2], [0, 5], [0, 8], [0, 8], [0, 10]]); | ||
|
||
var cleaned = turf.cleanCoords(line).geometry.coordinates; | ||
//= [[0, 0], [0, 10]] | ||
``` | ||
|
||
Returns **([Geometry](http://geojson.org/geojson-spec.html#geometry) \| [Feature](http://geojson.org/geojson-spec.html#feature-objects)<any>)** 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 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
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 | ||
* geometry x 3,053,905 ops/sec ±1.84% (87 runs sampled) | ||
* multiline x 3,943,840 ops/sec ±2.60% (85 runs sampled) | ||
* multipoint x 465,553 ops/sec ±1.04% (89 runs sampled) | ||
* multipolygon x 2,046,659 ops/sec ±0.77% (91 runs sampled) | ||
* point x 22,318,913 ops/sec ±1.20% (86 runs sampled) | ||
* polygon-with-hole x 3,109,098 ops/sec ±2.10% (91 runs sampled) | ||
* polygon x 4,603,124 ops/sec ±1.99% (84 runs sampled) | ||
* simple-line x 7,732,876 ops/sec ±1.18% (86 runs sampled) | ||
* triangle x 4,950,167 ops/sec ±1.36% (89 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, true); | ||
console.timeEnd(name); | ||
suite.add(name, () => cleanCoords(geojson, true)); | ||
}); | ||
|
||
suite | ||
.on('cycle', e => console.log(String(e.target))) | ||
.on('complete', () => {}) | ||
.run(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
var clone = require('@turf/clone'); | ||
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, mutate); | ||
break; | ||
case 'MultiLineString': | ||
case 'Polygon': | ||
for (var i = 0; i < coords.length; i++) { | ||
var line = coords[i]; | ||
newCoords.push(cleanCoords(line)); | ||
} | ||
break; | ||
case 'MultiPolygon': | ||
for (var j = 0; j < coords.length; j++) { | ||
var polys = coords[j]; | ||
var polyPoints = []; | ||
for (var p = 0; p < polys.length; p++) { | ||
var ring = polys[p]; | ||
polyPoints.push(cleanCoords(ring)); | ||
} | ||
newCoords.push(polyPoints); | ||
} | ||
break; | ||
case 'Point': | ||
return geojson; | ||
case 'MultiPoint': | ||
var existing = {}; | ||
for (var i = 0; i < coords.length; i++) { | ||
var point = coords[i]; | ||
var key = point.join('-'); | ||
if (!existing.hasOwnProperty(key)) { | ||
newCoords.push(point); | ||
existing[key] = true | ||
} | ||
} | ||
break; | ||
default: | ||
throw new Error(type + ' geometry not supported'); | ||
} | ||
|
||
if (mutate !== true) geojson = clone(geojson); | ||
if (geojson.coordinates) geojson.coordinates = newCoords; | ||
else geojson.geometry.coordinates = newCoords; | ||
return geojson; | ||
}; | ||
|
||
/** | ||
* Clean Coords | ||
* | ||
* @private | ||
* @param {Array<number>|LineString} line Line | ||
*/ | ||
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 | ||
* | ||
* @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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/helpers": "4.5.2", | ||
"benchmark": "^2.1.4", | ||
"write-json-file": "^2.2.0", | ||
"load-json-file": "^2.0.0", | ||
"tape": "^4.6.3" | ||
}, | ||
"dependencies": { | ||
"@turf/clone": "4.5.2", | ||
"@turf/invariant": "4.5.2" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
const fs = require('fs'); | ||
const test = require('tape'); | ||
const path = require('path'); | ||
const load = require('load-json-file'); | ||
const {multiPoint, lineString, multiPolygon} = require('@turf/helpers'); | ||
const write = require('write-json-file'); | ||
const cleanCoords = require('./'); | ||
|
||
const directories = { | ||
in: path.join(__dirname, 'test', 'in') + path.sep, | ||
out: path.join(__dirname, 'test', 'out') + path.sep | ||
}; | ||
|
||
const fixtures = fs.readdirSync(directories.in).map(filename => { | ||
return { | ||
filename, | ||
name: path.parse(filename).name, | ||
geojson: load.sync(directories.in + filename) | ||
}; | ||
}); | ||
|
||
test('turf-clean-coords', t => { | ||
for (const {filename, name, geojson} of fixtures) { | ||
const results = cleanCoords(geojson); | ||
|
||
if (process.env.REGEN) write.sync(directories.out + filename, results); | ||
t.deepEqual(results, load.sync(directories.out + filename), name); | ||
} | ||
t.end(); | ||
}); | ||
|
||
test('turf-clean-coords -- extras', t => { | ||
t.equal(cleanCoords(multiPoint([[0, 0], [0, 0], [2, 2]])).geometry.coordinates.length, 2); | ||
t.end(); | ||
}); | ||
|
||
test('turf-clean-coords -- throws', t => { | ||
t.throws(() => cleanCoords(null), /geojson is required/, 'missing geojson'); | ||
t.end(); | ||
}); | ||
|
||
test('turf-clean-coords -- prevent input mutation', t => { | ||
const line = lineString([[0, 0], [1, 1], [2, 2]], {foo: 'bar'}); | ||
cleanCoords(line); | ||
const lineBefore = JSON.parse(JSON.stringify(line)); | ||
t.deepEqual(lineBefore, line, 'line should NOT be mutated'); | ||
|
||
const multiPoly = multiPolygon([ | ||
[[[0, 0], [1, 1], [2, 2], [2, 0], [0, 0]]], | ||
[[[0, 0], [0, 5], [5, 5], [5, 5], [5, 0], [0, 0]]] | ||
], {hello: 'world'}); | ||
const multiPolyBefore = JSON.parse(JSON.stringify(multiPoly)); | ||
cleanCoords(multiPoly); | ||
t.deepEqual(multiPolyBefore, multiPoly, 'multiPolygon should NOT be mutated'); | ||
|
||
const cleanLine = cleanCoords(line, true); | ||
t.deepEqual(cleanLine, line, 'line should be mutated'); | ||
t.end(); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@DenisCarriere this is really smart! 🤓 👍
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks 🤓 !