diff --git a/src/nice.js b/src/nice.js index 1ef2de7..83982e6 100644 --- a/src/nice.js +++ b/src/nice.js @@ -1,6 +1,7 @@ import {tickIncrement} from "./ticks.js"; export default function nice(start, stop, count) { + if (count > 0) count = Math.max(count, start < 0 && stop > 0 ? 2 : 1); let prestep; while (true) { const step = tickIncrement(start, stop, count); diff --git a/test/bin-test.js b/test/bin-test.js index d015161..052140d 100644 --- a/test/bin-test.js +++ b/test/bin-test.js @@ -105,6 +105,16 @@ it("bin.thresholds(number) sets the approximate number of bin thresholds", () => ]); }); +it("bin() keeps finite bounds when one threshold spans zero", () => { + const bins = bin().thresholds(1)([-1.4, 5.6]); + assert.strictEqual(bins.flat().length, 2); + for (const {x0, x1} of bins) { + assert(Number.isFinite(x0)); + assert(Number.isFinite(x1)); + } + assert.deepStrictEqual(bins, [box([-1.4], -10, 0), box([5.6], 0, 10)]); +}); + it("bin.thresholds(array) sets the bin thresholds", () => { const h = bin().thresholds([10, 20]); assert.deepStrictEqual(h([0, 0, 0, 10, 30, 30]), [ diff --git a/test/nice-test.js b/test/nice-test.js index f652722..f2733cc 100644 --- a/test/nice-test.js +++ b/test/nice-test.js @@ -61,3 +61,15 @@ it("nice(start, stop, count) handles large steps precisely", () => { assert.deepStrictEqual(nice(0.929999999999999e10, 1.07e10, 5000), [0.92998e10, 1.07e10]); assert.deepStrictEqual(nice(-1.07e10, -0.929999999999999e10, 5000), [-1.07e10, -0.92998e10]); }); + +it("nice(start, stop, count) keeps intervals finite for small counts", () => { + for (const count of [0.5, 1, 1.5]) { + for (const [start, stop] of [[-1, 5], [-0.1, 0.2], [-5, 1], [-1, 1]]) { + const [a, b] = nice(start, stop, count); + assert(a <= start && b >= stop); + assert(b - a < 100 * (stop - start)); + } + } + assert.deepStrictEqual(nice(-1, 5, 1), [-10, 10]); + assert.deepStrictEqual(nice(0, 1, 0.5), [0, 1]); +});