diff --git a/src/log.js b/src/log.js index ad3f231..96dae6a 100644 --- a/src/log.js +++ b/src/log.js @@ -1,5 +1,5 @@ import {ticks} from "d3-array"; -import {format} from "d3-format"; +import {format, formatSpecifier} from "d3-format"; import nice from "./nice.js"; import {copy, transformer} from "./continuous.js"; import {initRange} from "./init.js"; @@ -111,10 +111,13 @@ export function loggish(transform) { }; scale.tickFormat = function(count, specifier) { + if (count == null) count = 10; if (specifier == null) specifier = base === 10 ? ".0e" : ","; - if (typeof specifier !== "function") specifier = format(specifier); + if (typeof specifier !== "function") { + if (!(base % 1) && (specifier = formatSpecifier(specifier)).precision == null) specifier.trim = true; + specifier = format(specifier); + } if (count === Infinity) return specifier; - if (count == null) count = 10; var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate? return function(d) { var i = d / pows(Math.round(logs(d))); diff --git a/test/log-test.js b/test/log-test.js index 42eb7a0..40816ca 100644 --- a/test/log-test.js +++ b/test/log-test.js @@ -401,7 +401,7 @@ it("log.tickFormat(count, format) returns a filtered format", () => { it("log.tickFormat(count, specifier) returns a filtered format", () => { const x = scaleLog().domain([1000.1, 1]); - assert.deepStrictEqual(x.ticks().map(x.tickFormat(10, ".1s")), [ + assert.deepStrictEqual(x.ticks().map(x.tickFormat(10, "s")), [ "1k", "", "", "", "", "", "", "300", "200", "100", "", "", "", "", "", "", "30", "20", "10", @@ -409,6 +409,35 @@ it("log.tickFormat(count, specifier) returns a filtered format", () => { ]); }); +it("log.tickFormat(count, specifier) trims trailing zeroes by default", () => { + const x = scaleLog().domain([100.1, 0.02]); + assert.deepStrictEqual(x.ticks().map(x.tickFormat(10, "f")), [ + "100", + "", "", "", "", "", "", "", "20", "10", + "", "", "", "", "", "", "", "2", "1", + "", "", "", "", "", "", "", "0.2", "0.1", + "", "", "", "", "", "", "", "0.02" + ]); +}); + +it("log.tickFormat(count, specifier) with base two trims trailing zeroes by default", () => { + const x = scaleLog().base(2).domain([100.1, 0.02]); + assert.deepStrictEqual(x.ticks().map(x.tickFormat(10, "f")), [ + "64", "32", "16", "8", "4", "2", "1", "0.5", "0.25", "0.125", "0.0625", "0.03125" + ]); +}); + +it("log.tickFormat(count, specifier) preserves trailing zeroes if needed", () => { + const x = scaleLog().domain([100.1, 0.02]); + assert.deepStrictEqual(x.ticks().map(x.tickFormat(10, ".1f")), [ + "100.0", + "", "", "", "", "", "", "", "20.0", "10.0", + "", "", "", "", "", "", "", "2.0", "1.0", + "", "", "", "", "", "", "", "0.2", "0.1", + "", "", "", "", "", "", "", "0.0" + ]); +}); + it("log.ticks() returns the empty array when the domain is degenerate", () => { const x = scaleLog(); assert.deepStrictEqual(x.domain([0, 1]).ticks(), []);