From 0aeeabdba10ac86e60e89456b933c0c5ce727f43 Mon Sep 17 00:00:00 2001 From: awais-ur-rehman Date: Sat, 7 Nov 2026 22:25:48 +0500 Subject: [PATCH] fix(nice): bound intervals crossing zero --- src/nice.js | 2 ++ test/bin-test.js | 10 ++++++++++ test/nice-test.js | 11 +++++++++++ 3 files changed, 23 insertions(+) diff --git a/src/nice.js b/src/nice.js index 1ef2de7..15ef2f4 100644 --- a/src/nice.js +++ b/src/nice.js @@ -1,6 +1,8 @@ import {tickIncrement} from "./ticks.js"; export default function nice(start, stop, count) { + // An interval crossing zero needs at least two ticks to converge. + if (start < 0 && stop > 0 && count > 0 && count < 2) count = 2; let prestep; while (true) { const step = tickIncrement(start, stop, count); diff --git a/test/bin-test.js b/test/bin-test.js index d015161..fc051e0 100644 --- a/test/bin-test.js +++ b/test/bin-test.js @@ -267,3 +267,13 @@ function box(bin, x0, x1) { function* iterable(array) { yield* array; } + + +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)); + } +}); diff --git a/test/nice-test.js b/test/nice-test.js index f652722..6c24e09 100644 --- a/test/nice-test.js +++ b/test/nice-test.js @@ -61,3 +61,14 @@ 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 crossing zero 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)); + } + } +});