From ddfa33e3ae69acee7fcbb6f5bad0f4b5d15e9eba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Rivi=C3=A8re?= Date: Mon, 17 Jun 2024 15:51:35 +0200 Subject: [PATCH] fix tickFormat on a collapsed domain (start == end) closes #286 closes https://github.com/observablehq/plot/issues/2076 --- src/tickFormat.js | 13 ++++++++++--- test/tickFormat-test.js | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/tickFormat.js b/src/tickFormat.js index 15fc54e..775b775 100644 --- a/src/tickFormat.js +++ b/src/tickFormat.js @@ -1,10 +1,10 @@ import {tickStep} from "d3-array"; import {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from "d3-format"; -export default function tickFormat(start, stop, count, specifier) { +export default function tickFormat(start, stop, count, specifierIn) { var step = tickStep(start, stop, count), precision; - specifier = formatSpecifier(specifier == null ? ",f" : specifier); + const specifier = formatSpecifier(specifierIn == null ? ",f" : specifierIn); switch (specifier.type) { case "s": { var value = Math.max(Math.abs(start), Math.abs(stop)); @@ -21,7 +21,14 @@ export default function tickFormat(start, stop, count, specifier) { } case "f": case "%": { - if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2; + if (specifier.precision == null) { + if (step === 0) { + if (specifierIn == null) specifier.trim = true; + } + else if (!isNaN(precision = precisionFixed(step))) { + specifier.precision = precision - (specifier.type === "%") * 2; + } + } break; } } diff --git a/test/tickFormat-test.js b/test/tickFormat-test.js index 613e477..0f92220 100644 --- a/test/tickFormat-test.js +++ b/test/tickFormat-test.js @@ -40,4 +40,20 @@ it("tickFormat(start, stop, count) uses the default precision when the domain is const f = tickFormat(0, NaN, 10); assert.strictEqual(f + "", " >-,f"); assert.strictEqual(f(0.12), "0.120000"); + + const f2 = tickFormat(0.12, NaN, 10); + assert.strictEqual(f2 + "", " >-,f"); + assert.strictEqual(f2(0.12), "0.120000"); +}); + +it("tickFormat(start, stop, count) uses the default precision with trimming when the domain is collapsed", () => { + const f = tickFormat(5.5, 5.5, 10); + assert.strictEqual(f + "", " >-,~f"); + assert.strictEqual(f(0), "0"); + assert.strictEqual(f(5.5), "5.5"); + assert.strictEqual(f(Math.PI), "3.141593"); + assert.strictEqual(f(-Math.PI), "−3.141593"); + assert.strictEqual(f(Math.PI * 1e7), "31,415,926.535898"); + assert.strictEqual(f(-Math.PI * 1e7), "−31,415,926.535898"); }); +