UNPKG

1.59 kBJavaScriptView Raw
1import formatTypes from "./formatTypes";
2
3// [[fill]align][sign][symbol][0][width][,][.precision][type]
4var re = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i;
5
6export default function(specifier) {
7 return new FormatSpecifier(specifier);
8};
9
10function FormatSpecifier(specifier) {
11 if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
12
13 var match,
14 fill = match[1] || " ",
15 align = match[2] || ">",
16 sign = match[3] || "-",
17 symbol = match[4] || "",
18 zero = !!match[5],
19 width = match[6] && +match[6],
20 comma = !!match[7],
21 precision = match[8] && +match[8].slice(1),
22 type = match[9] || "";
23
24 // The "n" type is an alias for ",g".
25 if (type === "n") comma = true, type = "g";
26
27 // Map invalid types to the default format.
28 else if (!formatTypes[type]) type = "";
29
30 // If zero fill is specified, padding goes after sign and before digits.
31 if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
32
33 this.fill = fill;
34 this.align = align;
35 this.sign = sign;
36 this.symbol = symbol;
37 this.zero = zero;
38 this.width = width;
39 this.comma = comma;
40 this.precision = precision;
41 this.type = type;
42}
43
44FormatSpecifier.prototype.toString = function() {
45 return this.fill
46 + this.align
47 + this.sign
48 + this.symbol
49 + (this.zero ? "0" : "")
50 + (this.width == null ? "" : Math.max(1, this.width | 0))
51 + (this.comma ? "," : "")
52 + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
53 + this.type;
54};