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