Skip to content

Commit 68fb588

Browse files
Filmbostock
andauthored
fix crash on missing top bin (#248)
* fix https://observablehq.com/@weiglemc/demonstrating-issue-with-d3-bins-in-d3v7-4-1-update the issue is that we have removed the last bin, but then want to assign the largest value to it because floor(x1) === x1 Co-authored-by: Mike Bostock <mbostock@gmail.com>
1 parent 364b3f3 commit 68fb588

2 files changed

Lines changed: 8 additions & 2 deletions

File tree

src/bin.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,14 @@ export default function bin() {
8585
if (step > 0) {
8686
for (i = 0; i < n; ++i) {
8787
if ((x = values[i]) != null && x0 <= x && x <= x1) {
88-
bins[Math.floor((x - x0) / step)].push(data[i]);
88+
bins[Math.min(m, Math.floor((x - x0) / step))].push(data[i]);
8989
}
9090
}
9191
} else if (step < 0) {
9292
for (i = 0; i < n; ++i) {
9393
if ((x = values[i]) != null && x0 <= x && x <= x1) {
9494
const j = Math.floor((x0 - x) * step);
95-
bins[j + (tz[j] <= x)].push(data[i]); // handle off-by-one due to rounding
95+
bins[Math.min(m, j + (tz[j] <= x))].push(data[i]); // handle off-by-one due to rounding
9696
}
9797
}
9898
}

test/bin-test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,12 @@ it("bin(data) assigns floating point values to the correct bins", () => {
235235
}
236236
});
237237

238+
it("bin(data) assigns integer values to the correct bins", () => {
239+
assert.deepStrictEqual(bin().domain([4, 5])([5]), [box([5], 4, 5)]);
240+
const eights = [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8];
241+
assert.deepStrictEqual(bin().domain([3, 8])(eights), [box([], 3, 4), box([], 4, 5), box([], 5, 6), box([], 6, 7), box(eights, 7, 8)]);
242+
});
243+
238244
function box(bin, x0, x1) {
239245
bin.x0 = x0;
240246
bin.x1 = x1;

0 commit comments

Comments
 (0)