Skip to content

Commit

Permalink
Fix #17 - implement format.toString.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Jan 7, 2016
1 parent 61a5e8a commit e92f3fb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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];
Expand All @@ -128,7 +134,7 @@ export default function(locale) {
}

return {
format: format,
format: newFormat,
formatPrefix: formatPrefix
};
};
5 changes: 5 additions & 0 deletions test/format-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/);
Expand Down

0 comments on commit e92f3fb

Please sign in to comment.