-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
221 lines (221 loc) · 5.69 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
* wiki: https://en.wikipedia.org/wiki/Printf_format_string
*/
export type Conf = {
align: 'left' | 'right';
type: string;
fill: string;
prefix: string;
digits: number;
minWidth: number;
hash: boolean;
percent: boolean;
string?: boolean;
};
export const rule = /^%([-+#0 ]*)?([1-9]\d*)?(?:\.(\d+))?([dfeEoxXi])(%)?$/;
type ParseResult = {
result: string;
conf: Conf;
};
const parse = (format: string): Conf | never => {
const match = format.match(rule);
if (match === null) {
throw new Error(
`Wrong formatting template: '${format}', should match the rule:${rule.toString()}`,
);
}
const conf: Conf = {
align: 'right',
type: '',
fill: ' ',
prefix: '',
digits: 6,
minWidth: 1,
hash: false,
percent: false,
};
const [_, flags, width, precision, type, percent] = match;
const isFloatType = ['f', 'e', 'E'].includes(type);
// eg:%.2d %.2o
if (precision !== undefined && !isFloatType) {
throw new Error(`the type of "${type}" should not have a percision width`);
}
conf.type = type;
conf.digits = precision !== undefined ? +precision : conf.digits;
conf.minWidth = width !== undefined ? +width : conf.minWidth;
conf.percent = percent === '%';
// parse flags
if (flags !== undefined) {
const segs = flags.split('');
let seg;
let exists = '';
while ((seg = segs.shift()) !== undefined) {
if (exists.includes(seg)) {
throw new Error(`Repeated flag of '${seg}' in '${format}'`);
}
exists += seg;
switch (seg) {
case '+':
conf.prefix = '+';
break;
case ' ':
if (conf.prefix !== '+') {
conf.prefix = ' ';
}
break;
case '0':
if (conf.align !== 'left') {
conf.fill = '0';
}
break;
case '-':
conf.align = 'left';
conf.fill = ' ';
break;
case '#':
conf.hash = true;
break;
}
}
}
return conf;
};
const printf = (format: string | Conf, target: number): ParseResult => {
if (typeof target !== 'number') {
throw new Error(`The second param must be a number,got '${target}'`);
}
const conf = typeof format === 'string' ? parse(format) : format;
const isFloatType = conf.type === 'f';
const isNegZero = Object.is(target, -0);
let result: number | string;
if (Object.is(target, -0)) {
conf.prefix = '-';
}
switch (conf.type) {
case 'd':
case 'i':
case 'f':
if (isFloatType) {
const ep = Math.pow(10, conf.digits);
result = Math.round(target * ep) / ep;
} else {
result = Math.round(target);
}
if (result < 0 || isNegZero) {
conf.prefix = '-';
result = result.toString().slice(1) || '0';
} else {
result = result.toString();
}
if (isFloatType) {
const segs = result.split('.');
const suffix = conf.digits
? '.' + (segs[1] || '0').padEnd(conf.digits, '0')
: '';
result = segs[0] + suffix;
conf.string = suffix.slice(-1) === '0';
}
break;
case 'o':
case 'x':
case 'X':
const isOctal = conf.type === 'o';
if (target < 0) {
throw new Error(
`a negative number ${target} can't format to ${
isOctal ? 'octal' : 'hex'
}`,
);
}
// always output string
conf.string = true;
// ignore '+' prefix
conf.prefix = '';
result = Math.floor(target);
if (isOctal) {
result = Math.abs(result).toString(8);
if (conf.hash) {
result = '0' + result;
} else {
result = result.toString();
}
} else {
result = Math.abs(result).toString(16);
const isUpper = conf.type === 'X';
if (conf.hash) {
conf.prefix += isUpper ? '0X' : '0x';
}
if (isUpper) {
result = result.toUpperCase();
}
}
break;
case 'e':
case 'E':
if (target < 0) {
throw new Error(`a negative number ${target} can't format to hex`);
}
conf.string = true;
const e = Math.floor(Math.log10(target));
let point = e.toString();
if (e < 0) {
if (e >= -9) {
point = '-0' + point.charAt(1);
}
} else {
if (e <= 9) {
point = '0' + point;
}
point = '+' + point;
}
point = conf.type + point;
const curConf: Conf = {
...conf,
type: 'f',
minWidth: conf.minWidth - point.length,
percent: false,
};
return {
conf: curConf,
result:
printf(
{
...curConf,
},
target / Math.pow(10, e),
).result +
point +
(conf.percent ? '%' : ''),
};
}
const width = conf.minWidth;
const fn = conf.align === 'right' ? 'padStart' : 'padEnd';
let needPad: boolean;
if (conf.fill === '0') {
const padLen = width - conf.prefix.length;
const nowResult = result as string;
result = conf.prefix + nowResult[fn](padLen, conf.fill);
needPad = padLen - nowResult.length > 0;
} else {
const nowResult = conf.prefix + result;
result = nowResult[fn](width, conf.fill);
needPad = width - nowResult.length > 0;
}
conf.string =
conf.string ||
conf.prefix === '+' ||
(conf.prefix === '-' && Number(result) === 0) ||
needPad;
if (conf.percent) {
result += '%';
conf.string = true;
}
return {
result,
conf,
};
};
export default (format: string, num: number): number | string => {
const { conf, result } = printf(format, num);
return conf.string ? result : Number(result);
};