-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathformat.js
326 lines (276 loc) · 8.75 KB
/
format.js
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// String.format for JavaScript
// Copyright (c) Daniel Mester Pirttijärvi 2009
// Altered by Anton Korenyushkin 2010
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
var core = require('core');
var base = require('base');
var culture = exports.culture = {
d: 'MM/dd/yyyy',
D: 'MMMM dd, yyyy',
t: 'hh:mm tt',
T: 'hh:mm:ss tt',
M: 'd MMMM',
Y: 'MMMM, yyyy',
s: 'yyyy-MM-ddTHH:mm:ss',
months: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
days: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
],
am: 'AM',
pm: 'PM',
decimalSeparator: '.',
thousandsSeparator: ',',
currencyFormat: '$#,0.00',
currencyDecimalSeparator: '.',
currencyThousandsSeparator: ','
};
function makeShort(name) {
return name.substr(0, 3);
}
with (culture)
base.update(
culture,
{
f: D + ' ' + t,
F: D + ' ' + T,
g: d + ' ' + t,
G: d + ' ' + T,
shortMonths: months.map(makeShort),
shortDays: days.map(makeShort)
});
// Handles the internal format processing of a number
function processNumber(input, format) {
var digits = 0,
forcedDigits = -1,
integralDigits = -1,
groupCounter = 0,
decimals = 0,
forcedDecimals = -1,
atDecimals = false,
unused = true, // True until a digit has been written to the output
out = [], // Used as a StringBuilder
c, i;
// Groups a string of digits by thousands and
// appends them to the string writer.
function append(value) {
for (var i = 0; i < value.length; i++) {
// Write number
out.push(value.charAt(i));
// Begin a new group?
if (groupCounter > 1 && groupCounter-- % 3 == 1)
out.push(format.t);
}
}
// Analyse format string
for (i = 0; i < format.f.length; i++) {
c = format.f.charAt(i);
decimals += atDecimals;
if (c == '0') {
if (atDecimals)
forcedDecimals = decimals;
else if (forcedDigits < 0)
forcedDigits = digits;
}
digits += !atDecimals && (c == '0' || c == '#');
atDecimals = atDecimals || c == '.';
}
forcedDigits = forcedDigits < 0 ? 1 : digits - forcedDigits;
// Negative value? Begin string with a dash
if (input < 0)
out.push('-');
// Round the input value to a specified number of decimals
input = (Math.round(Math.abs(input) * Math.pow(10, decimals)) /
Math.pow(10, decimals)).toString();
// Get integral length
integralDigits = input.indexOf('.');
integralDigits = integralDigits < 0 ? input.length : integralDigits;
// Set initial input cursor position
i = integralDigits - digits;
// Group thousands?
if (format.f.match(/^[^\.]*[0#],[0#]/))
groupCounter = Math.max(integralDigits, forcedDigits);
for (var f = 0; f < format.f.length; f++) {
c = format.f.charAt(f);
// Digit placeholder
if (c == '#' || c == '0') {
if (i < integralDigits) {
// In the integral part
if (i >= 0) {
if (unused)
append(input.substr(0, i));
append(input.charAt(i));
// Not yet inside the input number, force a zero?
} else if (i >= integralDigits - forcedDigits) {
append('0');
}
unused = false;
} else if (forcedDecimals-- > 0 || i < input.length) {
// In the fractional part
append(i >= input.length ? '0' : input.charAt(i));
}
i++;
// Radix point character according to current culture.
} else if (c == '.') {
if (input.length > ++i || forcedDecimals > 0)
out.push(format.r);
// Other characters are written as they are, except from commas
} else if (c !== ',') {
out.push(c);
}
}
return out.join('');
}
var original = Number.prototype.toString;
// Number Formatting
core.set(
Number.prototype, 'toString', core.HIDDEN,
function (format) {
if (!format)
return original.call(this);
if (typeof(format) == 'number' || format instanceof Number)
return original.call(this, format);
format += '';
var number = Number(this);
if (format == 'X') {
return original.call(Math.round(number), 16).toUpperCase();
} else if (format == 'x') {
return original.call(Math.round(number), 16);
} else {
// Write number as currency formatted string
var formatting = {
t: culture.thousandsSeparator,
r: culture.decimalSeparator
};
var g = '0.################';
var lowerFormat = format.toLowerCase();
if (lowerFormat === null || lowerFormat == 'g') {
format = g;
} else if (lowerFormat == 'n') {
format = '#,' + g;
} else if (lowerFormat == 'c') {
format = culture.currencyFormat;
formatting.r = culture.currencyDecimalSeparator;
formatting.t = culture.currencyThousandsSeparator;
} else if (lowerFormat == 'f') {
format = '0.00';
}
// Thousands
if (format.indexOf(',.') !== -1)
number /= 1000;
// Percent
if (format.indexOf('%') !== -1)
number *= 100;
// Split groups
// positive; negative; zero, where the two last ones are optional
var groups = format.split(';');
if (number < 0 && groups.length > 1) {
number *= -1;
formatting.f = groups[1];
} else {
formatting.f = groups[!number && groups.length > 2 ? 2 : 0];
}
return processNumber(number, formatting);
}
});
function numberPair(n) {
return (n < 10 ? '0' : '') + n;
}
// Date Formatting
core.set(
Date.prototype, 'toString', core.HIDDEN,
function (format) {
format = format || 'ddd MMM dd yyyy HH:mm:ss';
format += '';
if (format.length == 1 && culture.hasOwnProperty(format))
format = culture[format];
var self = this;
return format.replace(
/(d{1,4}|M{1,4}|yyyy|yy|HH|H|hh|h|mm|m|ss|s|tt)/g,
function () {
switch (arguments[0]) {
case 'dddd': return culture.days[self.getDay()];
case 'ddd': return culture.shortDays[self.getDay()];
case 'dd': return numberPair(self.getDate());
case 'd': return self.getDate();
case 'MMMM': return culture.months[self.getMonth()];
case 'MMM': return culture.shortMonths[self.getMonth()];
case 'MM': return numberPair(self.getMonth() + 1);
case 'M': return self.getMonth() + 1;
case 'yyyy': return self.getFullYear();
case 'yy': return self.getFullYear().toString().substr(2);
case 'HH': return numberPair(self.getHours());
case 'hh': return numberPair((self.getHours() - 1) % 12 + 1);
case 'H': return self.getHours();
case 'h': return (self.getHours() - 1) % 12 + 1;
case 'mm': return numberPair(self.getMinutes());
case 'm': return self.getMinutes();
case 'ss': return numberPair(self.getSeconds());
case 's': return self.getSeconds();
case 'tt': return self.getHours() < 12 ? culture.am : culture.pm;
default: return '';
}
});
});
core.set(
String.prototype, 'format', core.HIDDEN,
function(/* ... */) {
var outerArgs = arguments;
return this.replace(
/(\{*)\{((\d+)(\,(-?\d*))?(\:([^\}]*))?)\}/g,
function () {
var innerArgs = arguments;
if (innerArgs[1] && innerArgs[1].length % 2 == 1)
return innerArgs[0];
var arg = outerArgs[parseInt(innerArgs[3], 10)];
var formatted = (arg === undefined ? 'undefined'
: arg === null ? 'null'
: arg.toString(innerArgs[7]));
var align = +innerArgs[5] || 0;
var paddingLength = Math.abs(align) - formatted.length;
if (paddingLength > 0) {
// Build padding string
var padding = ' ';
while (padding.length < paddingLength)
padding += ' ';
// Add padding string at right side
formatted = align > 0 ? padding + formatted : formatted + padding;
}
return innerArgs[1] + formatted;
}).replace(/\{\{/g, '{').replace(/\}\}/g, '}');
});