UNPKG

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