UNPKG

1.17 kBJavaScriptView Raw
1// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
2var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
3
4export default function formatSpecifier(specifier) {
5 return new FormatSpecifier(specifier);
6}
7
8formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
9
10function FormatSpecifier(specifier) {
11 if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
12 var match;
13 this.fill = match[1] || " ";
14 this.align = match[2] || ">";
15 this.sign = match[3] || "-";
16 this.symbol = match[4] || "";
17 this.zero = !!match[5];
18 this.width = match[6] && +match[6];
19 this.comma = !!match[7];
20 this.precision = match[8] && +match[8].slice(1);
21 this.trim = !!match[9];
22 this.type = match[10] || "";
23}
24
25FormatSpecifier.prototype.toString = function() {
26 return this.fill
27 + this.align
28 + this.sign
29 + this.symbol
30 + (this.zero ? "0" : "")
31 + (this.width == null ? "" : Math.max(1, this.width | 0))
32 + (this.comma ? "," : "")
33 + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
34 + (this.trim ? "~" : "")
35 + this.type;
36};