Skip to content

Commit 755478c

Browse files
skip sorting when there is only one node (#28)
1 parent afc6213 commit 755478c

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

index.js

+9
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,15 @@ export default class Flatbush {
106106
throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
107107
}
108108

109+
if (this.numItems <= this.nodeSize) {
110+
// only one node, skip sorting and just fill the root box
111+
this._boxes[this._pos++] = this.minX;
112+
this._boxes[this._pos++] = this.minY;
113+
this._boxes[this._pos++] = this.maxX;
114+
this._boxes[this._pos++] = this.maxY;
115+
return;
116+
}
117+
109118
const width = this.maxX - this.minX;
110119
const height = this.maxY - this.minY;
111120
const hilbertValues = new Uint32Array(this.numItems);

test.js

+42
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,15 @@ function createIndex() {
3333
return index;
3434
}
3535

36+
function createSmallIndex(numItems, nodeSize) {
37+
const index = new Flatbush(numItems, nodeSize);
38+
for (let i = 0; i < 4 * numItems; i += 4) {
39+
index.add(data[i], data[i + 1], data[i + 2], data[i + 3]);
40+
}
41+
index.finish();
42+
return index;
43+
}
44+
3645

3746
test('indexes a bunch of rectangles', (t) => {
3847
const index = createIndex();
@@ -45,6 +54,39 @@ test('indexes a bunch of rectangles', (t) => {
4554
t.end();
4655
});
4756

57+
test('skips sorting less than nodeSize number of rectangles', (t) => {
58+
const numItems = 14;
59+
const nodeSize = 16;
60+
const index = createSmallIndex(numItems, nodeSize);
61+
62+
// compute expected root box extents
63+
let rootXMin = Infinity;
64+
let rootYMin = Infinity;
65+
let rootXMax = -Infinity;
66+
let rootYMax = -Infinity;
67+
for (let i = 0; i < 4 * numItems; i += 4) {
68+
if (data[i] < rootXMin) rootXMin = data[i];
69+
if (data[i + 1] < rootYMin) rootYMin = data[i + 1];
70+
if (data[i + 2] > rootXMax) rootXMax = data[i + 2];
71+
if (data[i + 3] > rootYMax) rootYMax = data[i + 3];
72+
}
73+
74+
// sort should be skipped, ordered progressing indices expected
75+
const expectedIndices = [];
76+
for (let i = 0; i < numItems; ++i) {
77+
expectedIndices.push(i);
78+
}
79+
expectedIndices.push(0);
80+
81+
const len = index._boxes.length;
82+
83+
t.same(index._indices, expectedIndices);
84+
t.equal(len, (numItems + 1) * 4);
85+
t.same(index._boxes.subarray(len - 4, len), [rootXMin, rootYMin, rootXMax, rootYMax]);
86+
87+
t.end();
88+
});
89+
4890
test('performs bbox search', (t) => {
4991
const index = createIndex();
5092

0 commit comments

Comments
 (0)