Debian Codegraph @

topojson/src/merge.js

raw
1 import {ring as ringArea} from "./area";
2 import {object} from "./feature";
3 import stitchArcs from "./stitchArcs";
4
5 export default function(topology) {
6 return object(topology, mergeArcs.apply(this, arguments));
7 }
8
9 export function mergeArcs(topology, objects) {
10 var polygonsByArc = {},
11 polygons = [],
12 components = [];
13
14 objects.forEach(function(o) {
15 if (o.type === "Polygon") register(o.arcs);
16 else if (o.type === "MultiPolygon") o.arcs.forEach(register);
17 });
18
19 function register(polygon) {
20 polygon.forEach(function(ring) {
21 ring.forEach(function(arc) {
22 (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
23 });
24 });
25 polygons.push(polygon);
26 }
27
28 function area(ring) {
29 return Math.abs(ringArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]));
30 }
31
32 polygons.forEach(function(polygon) {
33 if (!polygon._) {
34 var component = [],
35 neighbors = [polygon];
36 polygon._ = 1;
37 components.push(component);
38 while (polygon = neighbors.pop()) {
39 component.push(polygon);
40 polygon.forEach(function(ring) {
41 ring.forEach(function(arc) {
42 polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
43 if (!polygon._) {
44 polygon._ = 1;
45 neighbors.push(polygon);
46 }
47 });
48 });
49 });
50 }
51 }
52 });
53
54 polygons.forEach(function(polygon) {
55 delete polygon._;
56 });
57
58 return {
59 type: "MultiPolygon",
60 arcs: components.map(function(polygons) {
61 var arcs = [], n;
62
63 // Extract the exterior (unique) arcs.
64 polygons.forEach(function(polygon) {
65 polygon.forEach(function(ring) {
66 ring.forEach(function(arc) {
67 if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
68 arcs.push(arc);
69 }
70 });
71 });
72 });
73
74 // Stitch the arcs into one or more rings.
75 arcs = stitchArcs(topology, arcs);
76
77 // If more than one ring is returned,
78 // at most one of these rings can be the exterior;
79 // choose the one with the greatest absolute area.
80 if ((n = arcs.length) > 1) {
81 for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) {
82 if ((ki = area(arcs[i])) > k) {
83 t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki;
84 }
85 }
86 }
87
88 return arcs;
89 })
90 };
91 }