From e92f3fb68665da6fd2a0948b81ea5c007b6d5903 Mon Sep 17 00:00:00 2001 From: Mike Bostock Date: Thu, 7 Jan 2016 13:50:48 -0800 Subject: [PATCH] Fix #17 - implement format.toString. --- src/locale.js | 14 ++++++++++---- test/format-test.js | 5 +++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/locale.js b/src/locale.js index b500b10..70eba3e 100644 --- a/src/locale.js +++ b/src/locale.js @@ -15,7 +15,7 @@ export default function(locale) { currency = locale.currency, decimal = locale.decimal; - function format(specifier) { + function newFormat(specifier) { specifier = formatSpecifier(specifier); var fill = specifier.fill, @@ -47,7 +47,7 @@ export default function(locale) { : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); - return function(value) { + function format(value) { var valuePrefix = prefix, valueSuffix = suffix; @@ -115,10 +115,16 @@ export default function(locale) { } return padding + valuePrefix + value + valueSuffix; }; + + format.toString = function() { + return specifier + ""; + }; + + return format; } function formatPrefix(specifier, value) { - var f = format((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), + var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3]; @@ -128,7 +134,7 @@ export default function(locale) { } return { - format: format, + format: newFormat, formatPrefix: formatPrefix }; }; diff --git a/test/format-test.js b/test/format-test.js index a1e962d..c667eb9 100644 --- a/test/format-test.js +++ b/test/format-test.js @@ -6,6 +6,11 @@ tape("format(specifier)(number) returns a string", function(test) { test.end(); }); +tape("format(specifier).toString() returns the normalized specifier", function(test) { + test.equal(format.format("d") + "", " >-d"); + test.end(); +}); + tape("format(specifier) throws an error for invalid formats", function(test) { test.throws(function() { format.format("foo"); }, /invalid format: foo/); test.throws(function() { format.format(".-2s"); }, /invalid format: \.-2s/);