@hhfenpm/utils 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3445 @@
1
+ 'use strict';
2
+
3
+ function _typeof(o) {
4
+ "@babel/helpers - typeof";
5
+
6
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
7
+ return typeof o;
8
+ } : function (o) {
9
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
10
+ }, _typeof(o);
11
+ }
12
+
13
+ function requiredArgs(required, args) {
14
+ if (args.length < required) {
15
+ throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
16
+ }
17
+ }
18
+
19
+ /**
20
+ * @name isDate
21
+ * @category Common Helpers
22
+ * @summary Is the given value a date?
23
+ *
24
+ * @description
25
+ * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
26
+ *
27
+ * @param {*} value - the value to check
28
+ * @returns {boolean} true if the given value is a date
29
+ * @throws {TypeError} 1 arguments required
30
+ *
31
+ * @example
32
+ * // For a valid date:
33
+ * const result = isDate(new Date())
34
+ * //=> true
35
+ *
36
+ * @example
37
+ * // For an invalid date:
38
+ * const result = isDate(new Date(NaN))
39
+ * //=> true
40
+ *
41
+ * @example
42
+ * // For some value:
43
+ * const result = isDate('2014-02-31')
44
+ * //=> false
45
+ *
46
+ * @example
47
+ * // For an object:
48
+ * const result = isDate({})
49
+ * //=> false
50
+ */
51
+ function isDate(value) {
52
+ requiredArgs(1, arguments);
53
+ return value instanceof Date || _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
54
+ }
55
+
56
+ /**
57
+ * @name toDate
58
+ * @category Common Helpers
59
+ * @summary Convert the given argument to an instance of Date.
60
+ *
61
+ * @description
62
+ * Convert the given argument to an instance of Date.
63
+ *
64
+ * If the argument is an instance of Date, the function returns its clone.
65
+ *
66
+ * If the argument is a number, it is treated as a timestamp.
67
+ *
68
+ * If the argument is none of the above, the function returns Invalid Date.
69
+ *
70
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
71
+ *
72
+ * @param {Date|Number} argument - the value to convert
73
+ * @returns {Date} the parsed date in the local time zone
74
+ * @throws {TypeError} 1 argument required
75
+ *
76
+ * @example
77
+ * // Clone the date:
78
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
79
+ * //=> Tue Feb 11 2014 11:30:30
80
+ *
81
+ * @example
82
+ * // Convert the timestamp to date:
83
+ * const result = toDate(1392098430000)
84
+ * //=> Tue Feb 11 2014 11:30:30
85
+ */
86
+ function toDate(argument) {
87
+ requiredArgs(1, arguments);
88
+ var argStr = Object.prototype.toString.call(argument);
89
+
90
+ // Clone the date
91
+ if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
92
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
93
+ return new Date(argument.getTime());
94
+ } else if (typeof argument === 'number' || argStr === '[object Number]') {
95
+ return new Date(argument);
96
+ } else {
97
+ if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
98
+ // eslint-disable-next-line no-console
99
+ console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
100
+ // eslint-disable-next-line no-console
101
+ console.warn(new Error().stack);
102
+ }
103
+ return new Date(NaN);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * @name isValid
109
+ * @category Common Helpers
110
+ * @summary Is the given date valid?
111
+ *
112
+ * @description
113
+ * Returns false if argument is Invalid Date and true otherwise.
114
+ * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
115
+ * Invalid Date is a Date, whose time value is NaN.
116
+ *
117
+ * Time value of Date: http://es5.github.io/#x15.9.1.1
118
+ *
119
+ * @param {*} date - the date to check
120
+ * @returns {Boolean} the date is valid
121
+ * @throws {TypeError} 1 argument required
122
+ *
123
+ * @example
124
+ * // For the valid date:
125
+ * const result = isValid(new Date(2014, 1, 31))
126
+ * //=> true
127
+ *
128
+ * @example
129
+ * // For the value, convertable into a date:
130
+ * const result = isValid(1393804800000)
131
+ * //=> true
132
+ *
133
+ * @example
134
+ * // For the invalid date:
135
+ * const result = isValid(new Date(''))
136
+ * //=> false
137
+ */
138
+ function isValid(dirtyDate) {
139
+ requiredArgs(1, arguments);
140
+ if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
141
+ return false;
142
+ }
143
+ var date = toDate(dirtyDate);
144
+ return !isNaN(Number(date));
145
+ }
146
+
147
+ function toInteger(dirtyNumber) {
148
+ if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
149
+ return NaN;
150
+ }
151
+ var number = Number(dirtyNumber);
152
+ if (isNaN(number)) {
153
+ return number;
154
+ }
155
+ return number < 0 ? Math.ceil(number) : Math.floor(number);
156
+ }
157
+
158
+ /**
159
+ * @name addMilliseconds
160
+ * @category Millisecond Helpers
161
+ * @summary Add the specified number of milliseconds to the given date.
162
+ *
163
+ * @description
164
+ * Add the specified number of milliseconds to the given date.
165
+ *
166
+ * @param {Date|Number} date - the date to be changed
167
+ * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
168
+ * @returns {Date} the new date with the milliseconds added
169
+ * @throws {TypeError} 2 arguments required
170
+ *
171
+ * @example
172
+ * // Add 750 milliseconds to 10 July 2014 12:45:30.000:
173
+ * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
174
+ * //=> Thu Jul 10 2014 12:45:30.750
175
+ */
176
+ function addMilliseconds(dirtyDate, dirtyAmount) {
177
+ requiredArgs(2, arguments);
178
+ var timestamp = toDate(dirtyDate).getTime();
179
+ var amount = toInteger(dirtyAmount);
180
+ return new Date(timestamp + amount);
181
+ }
182
+
183
+ /**
184
+ * @name subMilliseconds
185
+ * @category Millisecond Helpers
186
+ * @summary Subtract the specified number of milliseconds from the given date.
187
+ *
188
+ * @description
189
+ * Subtract the specified number of milliseconds from the given date.
190
+ *
191
+ * @param {Date|Number} date - the date to be changed
192
+ * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
193
+ * @returns {Date} the new date with the milliseconds subtracted
194
+ * @throws {TypeError} 2 arguments required
195
+ *
196
+ * @example
197
+ * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
198
+ * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
199
+ * //=> Thu Jul 10 2014 12:45:29.250
200
+ */
201
+ function subMilliseconds(dirtyDate, dirtyAmount) {
202
+ requiredArgs(2, arguments);
203
+ var amount = toInteger(dirtyAmount);
204
+ return addMilliseconds(dirtyDate, -amount);
205
+ }
206
+
207
+ var MILLISECONDS_IN_DAY = 86400000;
208
+ function getUTCDayOfYear(dirtyDate) {
209
+ requiredArgs(1, arguments);
210
+ var date = toDate(dirtyDate);
211
+ var timestamp = date.getTime();
212
+ date.setUTCMonth(0, 1);
213
+ date.setUTCHours(0, 0, 0, 0);
214
+ var startOfYearTimestamp = date.getTime();
215
+ var difference = timestamp - startOfYearTimestamp;
216
+ return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
217
+ }
218
+
219
+ function startOfUTCISOWeek(dirtyDate) {
220
+ requiredArgs(1, arguments);
221
+ var weekStartsOn = 1;
222
+ var date = toDate(dirtyDate);
223
+ var day = date.getUTCDay();
224
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
225
+ date.setUTCDate(date.getUTCDate() - diff);
226
+ date.setUTCHours(0, 0, 0, 0);
227
+ return date;
228
+ }
229
+
230
+ function getUTCISOWeekYear(dirtyDate) {
231
+ requiredArgs(1, arguments);
232
+ var date = toDate(dirtyDate);
233
+ var year = date.getUTCFullYear();
234
+ var fourthOfJanuaryOfNextYear = new Date(0);
235
+ fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
236
+ fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
237
+ var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
238
+ var fourthOfJanuaryOfThisYear = new Date(0);
239
+ fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
240
+ fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
241
+ var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
242
+ if (date.getTime() >= startOfNextYear.getTime()) {
243
+ return year + 1;
244
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
245
+ return year;
246
+ } else {
247
+ return year - 1;
248
+ }
249
+ }
250
+
251
+ function startOfUTCISOWeekYear(dirtyDate) {
252
+ requiredArgs(1, arguments);
253
+ var year = getUTCISOWeekYear(dirtyDate);
254
+ var fourthOfJanuary = new Date(0);
255
+ fourthOfJanuary.setUTCFullYear(year, 0, 4);
256
+ fourthOfJanuary.setUTCHours(0, 0, 0, 0);
257
+ var date = startOfUTCISOWeek(fourthOfJanuary);
258
+ return date;
259
+ }
260
+
261
+ var MILLISECONDS_IN_WEEK$1 = 604800000;
262
+ function getUTCISOWeek(dirtyDate) {
263
+ requiredArgs(1, arguments);
264
+ var date = toDate(dirtyDate);
265
+ var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
266
+
267
+ // Round the number of days to the nearest integer
268
+ // because the number of milliseconds in a week is not constant
269
+ // (e.g. it's different in the week of the daylight saving time clock shift)
270
+ return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
271
+ }
272
+
273
+ var defaultOptions = {};
274
+ function getDefaultOptions() {
275
+ return defaultOptions;
276
+ }
277
+
278
+ function startOfUTCWeek(dirtyDate, options) {
279
+ var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
280
+ requiredArgs(1, arguments);
281
+ var defaultOptions = getDefaultOptions();
282
+ var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
283
+
284
+ // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
285
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
286
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
287
+ }
288
+ var date = toDate(dirtyDate);
289
+ var day = date.getUTCDay();
290
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
291
+ date.setUTCDate(date.getUTCDate() - diff);
292
+ date.setUTCHours(0, 0, 0, 0);
293
+ return date;
294
+ }
295
+
296
+ function getUTCWeekYear(dirtyDate, options) {
297
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
298
+ requiredArgs(1, arguments);
299
+ var date = toDate(dirtyDate);
300
+ var year = date.getUTCFullYear();
301
+ var defaultOptions = getDefaultOptions();
302
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
303
+
304
+ // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
305
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
306
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
307
+ }
308
+ var firstWeekOfNextYear = new Date(0);
309
+ firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
310
+ firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
311
+ var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
312
+ var firstWeekOfThisYear = new Date(0);
313
+ firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
314
+ firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
315
+ var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
316
+ if (date.getTime() >= startOfNextYear.getTime()) {
317
+ return year + 1;
318
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
319
+ return year;
320
+ } else {
321
+ return year - 1;
322
+ }
323
+ }
324
+
325
+ function startOfUTCWeekYear(dirtyDate, options) {
326
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
327
+ requiredArgs(1, arguments);
328
+ var defaultOptions = getDefaultOptions();
329
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
330
+ var year = getUTCWeekYear(dirtyDate, options);
331
+ var firstWeek = new Date(0);
332
+ firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
333
+ firstWeek.setUTCHours(0, 0, 0, 0);
334
+ var date = startOfUTCWeek(firstWeek, options);
335
+ return date;
336
+ }
337
+
338
+ var MILLISECONDS_IN_WEEK = 604800000;
339
+ function getUTCWeek(dirtyDate, options) {
340
+ requiredArgs(1, arguments);
341
+ var date = toDate(dirtyDate);
342
+ var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
343
+
344
+ // Round the number of days to the nearest integer
345
+ // because the number of milliseconds in a week is not constant
346
+ // (e.g. it's different in the week of the daylight saving time clock shift)
347
+ return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
348
+ }
349
+
350
+ function addLeadingZeros(number, targetLength) {
351
+ var sign = number < 0 ? '-' : '';
352
+ var output = Math.abs(number).toString();
353
+ while (output.length < targetLength) {
354
+ output = '0' + output;
355
+ }
356
+ return sign + output;
357
+ }
358
+
359
+ /*
360
+ * | | Unit | | Unit |
361
+ * |-----|--------------------------------|-----|--------------------------------|
362
+ * | a | AM, PM | A* | |
363
+ * | d | Day of month | D | |
364
+ * | h | Hour [1-12] | H | Hour [0-23] |
365
+ * | m | Minute | M | Month |
366
+ * | s | Second | S | Fraction of second |
367
+ * | y | Year (abs) | Y | |
368
+ *
369
+ * Letters marked by * are not implemented but reserved by Unicode standard.
370
+ */
371
+ var formatters$2 = {
372
+ // Year
373
+ y: function y(date, token) {
374
+ // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
375
+ // | Year | y | yy | yyy | yyyy | yyyyy |
376
+ // |----------|-------|----|-------|-------|-------|
377
+ // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
378
+ // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
379
+ // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
380
+ // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
381
+ // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
382
+
383
+ var signedYear = date.getUTCFullYear();
384
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
385
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
386
+ return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
387
+ },
388
+ // Month
389
+ M: function M(date, token) {
390
+ var month = date.getUTCMonth();
391
+ return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
392
+ },
393
+ // Day of the month
394
+ d: function d(date, token) {
395
+ return addLeadingZeros(date.getUTCDate(), token.length);
396
+ },
397
+ // AM or PM
398
+ a: function a(date, token) {
399
+ var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
400
+ switch (token) {
401
+ case 'a':
402
+ case 'aa':
403
+ return dayPeriodEnumValue.toUpperCase();
404
+ case 'aaa':
405
+ return dayPeriodEnumValue;
406
+ case 'aaaaa':
407
+ return dayPeriodEnumValue[0];
408
+ case 'aaaa':
409
+ default:
410
+ return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
411
+ }
412
+ },
413
+ // Hour [1-12]
414
+ h: function h(date, token) {
415
+ return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
416
+ },
417
+ // Hour [0-23]
418
+ H: function H(date, token) {
419
+ return addLeadingZeros(date.getUTCHours(), token.length);
420
+ },
421
+ // Minute
422
+ m: function m(date, token) {
423
+ return addLeadingZeros(date.getUTCMinutes(), token.length);
424
+ },
425
+ // Second
426
+ s: function s(date, token) {
427
+ return addLeadingZeros(date.getUTCSeconds(), token.length);
428
+ },
429
+ // Fraction of second
430
+ S: function S(date, token) {
431
+ var numberOfDigits = token.length;
432
+ var milliseconds = date.getUTCMilliseconds();
433
+ var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
434
+ return addLeadingZeros(fractionalSeconds, token.length);
435
+ }
436
+ };
437
+ var lightFormatters = formatters$2;
438
+
439
+ var dayPeriodEnum = {
440
+ am: 'am',
441
+ pm: 'pm',
442
+ midnight: 'midnight',
443
+ noon: 'noon',
444
+ morning: 'morning',
445
+ afternoon: 'afternoon',
446
+ evening: 'evening',
447
+ night: 'night'
448
+ };
449
+ /*
450
+ * | | Unit | | Unit |
451
+ * |-----|--------------------------------|-----|--------------------------------|
452
+ * | a | AM, PM | A* | Milliseconds in day |
453
+ * | b | AM, PM, noon, midnight | B | Flexible day period |
454
+ * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
455
+ * | d | Day of month | D | Day of year |
456
+ * | e | Local day of week | E | Day of week |
457
+ * | f | | F* | Day of week in month |
458
+ * | g* | Modified Julian day | G | Era |
459
+ * | h | Hour [1-12] | H | Hour [0-23] |
460
+ * | i! | ISO day of week | I! | ISO week of year |
461
+ * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
462
+ * | k | Hour [1-24] | K | Hour [0-11] |
463
+ * | l* | (deprecated) | L | Stand-alone month |
464
+ * | m | Minute | M | Month |
465
+ * | n | | N | |
466
+ * | o! | Ordinal number modifier | O | Timezone (GMT) |
467
+ * | p! | Long localized time | P! | Long localized date |
468
+ * | q | Stand-alone quarter | Q | Quarter |
469
+ * | r* | Related Gregorian year | R! | ISO week-numbering year |
470
+ * | s | Second | S | Fraction of second |
471
+ * | t! | Seconds timestamp | T! | Milliseconds timestamp |
472
+ * | u | Extended year | U* | Cyclic year |
473
+ * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
474
+ * | w | Local week of year | W* | Week of month |
475
+ * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
476
+ * | y | Year (abs) | Y | Local week-numbering year |
477
+ * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
478
+ *
479
+ * Letters marked by * are not implemented but reserved by Unicode standard.
480
+ *
481
+ * Letters marked by ! are non-standard, but implemented by date-fns:
482
+ * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
483
+ * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
484
+ * i.e. 7 for Sunday, 1 for Monday, etc.
485
+ * - `I` is ISO week of year, as opposed to `w` which is local week of year.
486
+ * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
487
+ * `R` is supposed to be used in conjunction with `I` and `i`
488
+ * for universal ISO week-numbering date, whereas
489
+ * `Y` is supposed to be used in conjunction with `w` and `e`
490
+ * for week-numbering date specific to the locale.
491
+ * - `P` is long localized date format
492
+ * - `p` is long localized time format
493
+ */
494
+
495
+ var formatters = {
496
+ // Era
497
+ G: function G(date, token, localize) {
498
+ var era = date.getUTCFullYear() > 0 ? 1 : 0;
499
+ switch (token) {
500
+ // AD, BC
501
+ case 'G':
502
+ case 'GG':
503
+ case 'GGG':
504
+ return localize.era(era, {
505
+ width: 'abbreviated'
506
+ });
507
+ // A, B
508
+ case 'GGGGG':
509
+ return localize.era(era, {
510
+ width: 'narrow'
511
+ });
512
+ // Anno Domini, Before Christ
513
+ case 'GGGG':
514
+ default:
515
+ return localize.era(era, {
516
+ width: 'wide'
517
+ });
518
+ }
519
+ },
520
+ // Year
521
+ y: function y(date, token, localize) {
522
+ // Ordinal number
523
+ if (token === 'yo') {
524
+ var signedYear = date.getUTCFullYear();
525
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
526
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
527
+ return localize.ordinalNumber(year, {
528
+ unit: 'year'
529
+ });
530
+ }
531
+ return lightFormatters.y(date, token);
532
+ },
533
+ // Local week-numbering year
534
+ Y: function Y(date, token, localize, options) {
535
+ var signedWeekYear = getUTCWeekYear(date, options);
536
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
537
+ var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
538
+
539
+ // Two digit year
540
+ if (token === 'YY') {
541
+ var twoDigitYear = weekYear % 100;
542
+ return addLeadingZeros(twoDigitYear, 2);
543
+ }
544
+
545
+ // Ordinal number
546
+ if (token === 'Yo') {
547
+ return localize.ordinalNumber(weekYear, {
548
+ unit: 'year'
549
+ });
550
+ }
551
+
552
+ // Padding
553
+ return addLeadingZeros(weekYear, token.length);
554
+ },
555
+ // ISO week-numbering year
556
+ R: function R(date, token) {
557
+ var isoWeekYear = getUTCISOWeekYear(date);
558
+
559
+ // Padding
560
+ return addLeadingZeros(isoWeekYear, token.length);
561
+ },
562
+ // Extended year. This is a single number designating the year of this calendar system.
563
+ // The main difference between `y` and `u` localizers are B.C. years:
564
+ // | Year | `y` | `u` |
565
+ // |------|-----|-----|
566
+ // | AC 1 | 1 | 1 |
567
+ // | BC 1 | 1 | 0 |
568
+ // | BC 2 | 2 | -1 |
569
+ // Also `yy` always returns the last two digits of a year,
570
+ // while `uu` pads single digit years to 2 characters and returns other years unchanged.
571
+ u: function u(date, token) {
572
+ var year = date.getUTCFullYear();
573
+ return addLeadingZeros(year, token.length);
574
+ },
575
+ // Quarter
576
+ Q: function Q(date, token, localize) {
577
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
578
+ switch (token) {
579
+ // 1, 2, 3, 4
580
+ case 'Q':
581
+ return String(quarter);
582
+ // 01, 02, 03, 04
583
+ case 'QQ':
584
+ return addLeadingZeros(quarter, 2);
585
+ // 1st, 2nd, 3rd, 4th
586
+ case 'Qo':
587
+ return localize.ordinalNumber(quarter, {
588
+ unit: 'quarter'
589
+ });
590
+ // Q1, Q2, Q3, Q4
591
+ case 'QQQ':
592
+ return localize.quarter(quarter, {
593
+ width: 'abbreviated',
594
+ context: 'formatting'
595
+ });
596
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
597
+ case 'QQQQQ':
598
+ return localize.quarter(quarter, {
599
+ width: 'narrow',
600
+ context: 'formatting'
601
+ });
602
+ // 1st quarter, 2nd quarter, ...
603
+ case 'QQQQ':
604
+ default:
605
+ return localize.quarter(quarter, {
606
+ width: 'wide',
607
+ context: 'formatting'
608
+ });
609
+ }
610
+ },
611
+ // Stand-alone quarter
612
+ q: function q(date, token, localize) {
613
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
614
+ switch (token) {
615
+ // 1, 2, 3, 4
616
+ case 'q':
617
+ return String(quarter);
618
+ // 01, 02, 03, 04
619
+ case 'qq':
620
+ return addLeadingZeros(quarter, 2);
621
+ // 1st, 2nd, 3rd, 4th
622
+ case 'qo':
623
+ return localize.ordinalNumber(quarter, {
624
+ unit: 'quarter'
625
+ });
626
+ // Q1, Q2, Q3, Q4
627
+ case 'qqq':
628
+ return localize.quarter(quarter, {
629
+ width: 'abbreviated',
630
+ context: 'standalone'
631
+ });
632
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
633
+ case 'qqqqq':
634
+ return localize.quarter(quarter, {
635
+ width: 'narrow',
636
+ context: 'standalone'
637
+ });
638
+ // 1st quarter, 2nd quarter, ...
639
+ case 'qqqq':
640
+ default:
641
+ return localize.quarter(quarter, {
642
+ width: 'wide',
643
+ context: 'standalone'
644
+ });
645
+ }
646
+ },
647
+ // Month
648
+ M: function M(date, token, localize) {
649
+ var month = date.getUTCMonth();
650
+ switch (token) {
651
+ case 'M':
652
+ case 'MM':
653
+ return lightFormatters.M(date, token);
654
+ // 1st, 2nd, ..., 12th
655
+ case 'Mo':
656
+ return localize.ordinalNumber(month + 1, {
657
+ unit: 'month'
658
+ });
659
+ // Jan, Feb, ..., Dec
660
+ case 'MMM':
661
+ return localize.month(month, {
662
+ width: 'abbreviated',
663
+ context: 'formatting'
664
+ });
665
+ // J, F, ..., D
666
+ case 'MMMMM':
667
+ return localize.month(month, {
668
+ width: 'narrow',
669
+ context: 'formatting'
670
+ });
671
+ // January, February, ..., December
672
+ case 'MMMM':
673
+ default:
674
+ return localize.month(month, {
675
+ width: 'wide',
676
+ context: 'formatting'
677
+ });
678
+ }
679
+ },
680
+ // Stand-alone month
681
+ L: function L(date, token, localize) {
682
+ var month = date.getUTCMonth();
683
+ switch (token) {
684
+ // 1, 2, ..., 12
685
+ case 'L':
686
+ return String(month + 1);
687
+ // 01, 02, ..., 12
688
+ case 'LL':
689
+ return addLeadingZeros(month + 1, 2);
690
+ // 1st, 2nd, ..., 12th
691
+ case 'Lo':
692
+ return localize.ordinalNumber(month + 1, {
693
+ unit: 'month'
694
+ });
695
+ // Jan, Feb, ..., Dec
696
+ case 'LLL':
697
+ return localize.month(month, {
698
+ width: 'abbreviated',
699
+ context: 'standalone'
700
+ });
701
+ // J, F, ..., D
702
+ case 'LLLLL':
703
+ return localize.month(month, {
704
+ width: 'narrow',
705
+ context: 'standalone'
706
+ });
707
+ // January, February, ..., December
708
+ case 'LLLL':
709
+ default:
710
+ return localize.month(month, {
711
+ width: 'wide',
712
+ context: 'standalone'
713
+ });
714
+ }
715
+ },
716
+ // Local week of year
717
+ w: function w(date, token, localize, options) {
718
+ var week = getUTCWeek(date, options);
719
+ if (token === 'wo') {
720
+ return localize.ordinalNumber(week, {
721
+ unit: 'week'
722
+ });
723
+ }
724
+ return addLeadingZeros(week, token.length);
725
+ },
726
+ // ISO week of year
727
+ I: function I(date, token, localize) {
728
+ var isoWeek = getUTCISOWeek(date);
729
+ if (token === 'Io') {
730
+ return localize.ordinalNumber(isoWeek, {
731
+ unit: 'week'
732
+ });
733
+ }
734
+ return addLeadingZeros(isoWeek, token.length);
735
+ },
736
+ // Day of the month
737
+ d: function d(date, token, localize) {
738
+ if (token === 'do') {
739
+ return localize.ordinalNumber(date.getUTCDate(), {
740
+ unit: 'date'
741
+ });
742
+ }
743
+ return lightFormatters.d(date, token);
744
+ },
745
+ // Day of year
746
+ D: function D(date, token, localize) {
747
+ var dayOfYear = getUTCDayOfYear(date);
748
+ if (token === 'Do') {
749
+ return localize.ordinalNumber(dayOfYear, {
750
+ unit: 'dayOfYear'
751
+ });
752
+ }
753
+ return addLeadingZeros(dayOfYear, token.length);
754
+ },
755
+ // Day of week
756
+ E: function E(date, token, localize) {
757
+ var dayOfWeek = date.getUTCDay();
758
+ switch (token) {
759
+ // Tue
760
+ case 'E':
761
+ case 'EE':
762
+ case 'EEE':
763
+ return localize.day(dayOfWeek, {
764
+ width: 'abbreviated',
765
+ context: 'formatting'
766
+ });
767
+ // T
768
+ case 'EEEEE':
769
+ return localize.day(dayOfWeek, {
770
+ width: 'narrow',
771
+ context: 'formatting'
772
+ });
773
+ // Tu
774
+ case 'EEEEEE':
775
+ return localize.day(dayOfWeek, {
776
+ width: 'short',
777
+ context: 'formatting'
778
+ });
779
+ // Tuesday
780
+ case 'EEEE':
781
+ default:
782
+ return localize.day(dayOfWeek, {
783
+ width: 'wide',
784
+ context: 'formatting'
785
+ });
786
+ }
787
+ },
788
+ // Local day of week
789
+ e: function e(date, token, localize, options) {
790
+ var dayOfWeek = date.getUTCDay();
791
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
792
+ switch (token) {
793
+ // Numerical value (Nth day of week with current locale or weekStartsOn)
794
+ case 'e':
795
+ return String(localDayOfWeek);
796
+ // Padded numerical value
797
+ case 'ee':
798
+ return addLeadingZeros(localDayOfWeek, 2);
799
+ // 1st, 2nd, ..., 7th
800
+ case 'eo':
801
+ return localize.ordinalNumber(localDayOfWeek, {
802
+ unit: 'day'
803
+ });
804
+ case 'eee':
805
+ return localize.day(dayOfWeek, {
806
+ width: 'abbreviated',
807
+ context: 'formatting'
808
+ });
809
+ // T
810
+ case 'eeeee':
811
+ return localize.day(dayOfWeek, {
812
+ width: 'narrow',
813
+ context: 'formatting'
814
+ });
815
+ // Tu
816
+ case 'eeeeee':
817
+ return localize.day(dayOfWeek, {
818
+ width: 'short',
819
+ context: 'formatting'
820
+ });
821
+ // Tuesday
822
+ case 'eeee':
823
+ default:
824
+ return localize.day(dayOfWeek, {
825
+ width: 'wide',
826
+ context: 'formatting'
827
+ });
828
+ }
829
+ },
830
+ // Stand-alone local day of week
831
+ c: function c(date, token, localize, options) {
832
+ var dayOfWeek = date.getUTCDay();
833
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
834
+ switch (token) {
835
+ // Numerical value (same as in `e`)
836
+ case 'c':
837
+ return String(localDayOfWeek);
838
+ // Padded numerical value
839
+ case 'cc':
840
+ return addLeadingZeros(localDayOfWeek, token.length);
841
+ // 1st, 2nd, ..., 7th
842
+ case 'co':
843
+ return localize.ordinalNumber(localDayOfWeek, {
844
+ unit: 'day'
845
+ });
846
+ case 'ccc':
847
+ return localize.day(dayOfWeek, {
848
+ width: 'abbreviated',
849
+ context: 'standalone'
850
+ });
851
+ // T
852
+ case 'ccccc':
853
+ return localize.day(dayOfWeek, {
854
+ width: 'narrow',
855
+ context: 'standalone'
856
+ });
857
+ // Tu
858
+ case 'cccccc':
859
+ return localize.day(dayOfWeek, {
860
+ width: 'short',
861
+ context: 'standalone'
862
+ });
863
+ // Tuesday
864
+ case 'cccc':
865
+ default:
866
+ return localize.day(dayOfWeek, {
867
+ width: 'wide',
868
+ context: 'standalone'
869
+ });
870
+ }
871
+ },
872
+ // ISO day of week
873
+ i: function i(date, token, localize) {
874
+ var dayOfWeek = date.getUTCDay();
875
+ var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
876
+ switch (token) {
877
+ // 2
878
+ case 'i':
879
+ return String(isoDayOfWeek);
880
+ // 02
881
+ case 'ii':
882
+ return addLeadingZeros(isoDayOfWeek, token.length);
883
+ // 2nd
884
+ case 'io':
885
+ return localize.ordinalNumber(isoDayOfWeek, {
886
+ unit: 'day'
887
+ });
888
+ // Tue
889
+ case 'iii':
890
+ return localize.day(dayOfWeek, {
891
+ width: 'abbreviated',
892
+ context: 'formatting'
893
+ });
894
+ // T
895
+ case 'iiiii':
896
+ return localize.day(dayOfWeek, {
897
+ width: 'narrow',
898
+ context: 'formatting'
899
+ });
900
+ // Tu
901
+ case 'iiiiii':
902
+ return localize.day(dayOfWeek, {
903
+ width: 'short',
904
+ context: 'formatting'
905
+ });
906
+ // Tuesday
907
+ case 'iiii':
908
+ default:
909
+ return localize.day(dayOfWeek, {
910
+ width: 'wide',
911
+ context: 'formatting'
912
+ });
913
+ }
914
+ },
915
+ // AM or PM
916
+ a: function a(date, token, localize) {
917
+ var hours = date.getUTCHours();
918
+ var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
919
+ switch (token) {
920
+ case 'a':
921
+ case 'aa':
922
+ return localize.dayPeriod(dayPeriodEnumValue, {
923
+ width: 'abbreviated',
924
+ context: 'formatting'
925
+ });
926
+ case 'aaa':
927
+ return localize.dayPeriod(dayPeriodEnumValue, {
928
+ width: 'abbreviated',
929
+ context: 'formatting'
930
+ }).toLowerCase();
931
+ case 'aaaaa':
932
+ return localize.dayPeriod(dayPeriodEnumValue, {
933
+ width: 'narrow',
934
+ context: 'formatting'
935
+ });
936
+ case 'aaaa':
937
+ default:
938
+ return localize.dayPeriod(dayPeriodEnumValue, {
939
+ width: 'wide',
940
+ context: 'formatting'
941
+ });
942
+ }
943
+ },
944
+ // AM, PM, midnight, noon
945
+ b: function b(date, token, localize) {
946
+ var hours = date.getUTCHours();
947
+ var dayPeriodEnumValue;
948
+ if (hours === 12) {
949
+ dayPeriodEnumValue = dayPeriodEnum.noon;
950
+ } else if (hours === 0) {
951
+ dayPeriodEnumValue = dayPeriodEnum.midnight;
952
+ } else {
953
+ dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
954
+ }
955
+ switch (token) {
956
+ case 'b':
957
+ case 'bb':
958
+ return localize.dayPeriod(dayPeriodEnumValue, {
959
+ width: 'abbreviated',
960
+ context: 'formatting'
961
+ });
962
+ case 'bbb':
963
+ return localize.dayPeriod(dayPeriodEnumValue, {
964
+ width: 'abbreviated',
965
+ context: 'formatting'
966
+ }).toLowerCase();
967
+ case 'bbbbb':
968
+ return localize.dayPeriod(dayPeriodEnumValue, {
969
+ width: 'narrow',
970
+ context: 'formatting'
971
+ });
972
+ case 'bbbb':
973
+ default:
974
+ return localize.dayPeriod(dayPeriodEnumValue, {
975
+ width: 'wide',
976
+ context: 'formatting'
977
+ });
978
+ }
979
+ },
980
+ // in the morning, in the afternoon, in the evening, at night
981
+ B: function B(date, token, localize) {
982
+ var hours = date.getUTCHours();
983
+ var dayPeriodEnumValue;
984
+ if (hours >= 17) {
985
+ dayPeriodEnumValue = dayPeriodEnum.evening;
986
+ } else if (hours >= 12) {
987
+ dayPeriodEnumValue = dayPeriodEnum.afternoon;
988
+ } else if (hours >= 4) {
989
+ dayPeriodEnumValue = dayPeriodEnum.morning;
990
+ } else {
991
+ dayPeriodEnumValue = dayPeriodEnum.night;
992
+ }
993
+ switch (token) {
994
+ case 'B':
995
+ case 'BB':
996
+ case 'BBB':
997
+ return localize.dayPeriod(dayPeriodEnumValue, {
998
+ width: 'abbreviated',
999
+ context: 'formatting'
1000
+ });
1001
+ case 'BBBBB':
1002
+ return localize.dayPeriod(dayPeriodEnumValue, {
1003
+ width: 'narrow',
1004
+ context: 'formatting'
1005
+ });
1006
+ case 'BBBB':
1007
+ default:
1008
+ return localize.dayPeriod(dayPeriodEnumValue, {
1009
+ width: 'wide',
1010
+ context: 'formatting'
1011
+ });
1012
+ }
1013
+ },
1014
+ // Hour [1-12]
1015
+ h: function h(date, token, localize) {
1016
+ if (token === 'ho') {
1017
+ var hours = date.getUTCHours() % 12;
1018
+ if (hours === 0) hours = 12;
1019
+ return localize.ordinalNumber(hours, {
1020
+ unit: 'hour'
1021
+ });
1022
+ }
1023
+ return lightFormatters.h(date, token);
1024
+ },
1025
+ // Hour [0-23]
1026
+ H: function H(date, token, localize) {
1027
+ if (token === 'Ho') {
1028
+ return localize.ordinalNumber(date.getUTCHours(), {
1029
+ unit: 'hour'
1030
+ });
1031
+ }
1032
+ return lightFormatters.H(date, token);
1033
+ },
1034
+ // Hour [0-11]
1035
+ K: function K(date, token, localize) {
1036
+ var hours = date.getUTCHours() % 12;
1037
+ if (token === 'Ko') {
1038
+ return localize.ordinalNumber(hours, {
1039
+ unit: 'hour'
1040
+ });
1041
+ }
1042
+ return addLeadingZeros(hours, token.length);
1043
+ },
1044
+ // Hour [1-24]
1045
+ k: function k(date, token, localize) {
1046
+ var hours = date.getUTCHours();
1047
+ if (hours === 0) hours = 24;
1048
+ if (token === 'ko') {
1049
+ return localize.ordinalNumber(hours, {
1050
+ unit: 'hour'
1051
+ });
1052
+ }
1053
+ return addLeadingZeros(hours, token.length);
1054
+ },
1055
+ // Minute
1056
+ m: function m(date, token, localize) {
1057
+ if (token === 'mo') {
1058
+ return localize.ordinalNumber(date.getUTCMinutes(), {
1059
+ unit: 'minute'
1060
+ });
1061
+ }
1062
+ return lightFormatters.m(date, token);
1063
+ },
1064
+ // Second
1065
+ s: function s(date, token, localize) {
1066
+ if (token === 'so') {
1067
+ return localize.ordinalNumber(date.getUTCSeconds(), {
1068
+ unit: 'second'
1069
+ });
1070
+ }
1071
+ return lightFormatters.s(date, token);
1072
+ },
1073
+ // Fraction of second
1074
+ S: function S(date, token) {
1075
+ return lightFormatters.S(date, token);
1076
+ },
1077
+ // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
1078
+ X: function X(date, token, _localize, options) {
1079
+ var originalDate = options._originalDate || date;
1080
+ var timezoneOffset = originalDate.getTimezoneOffset();
1081
+ if (timezoneOffset === 0) {
1082
+ return 'Z';
1083
+ }
1084
+ switch (token) {
1085
+ // Hours and optional minutes
1086
+ case 'X':
1087
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1088
+
1089
+ // Hours, minutes and optional seconds without `:` delimiter
1090
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1091
+ // so this token always has the same output as `XX`
1092
+ case 'XXXX':
1093
+ case 'XX':
1094
+ // Hours and minutes without `:` delimiter
1095
+ return formatTimezone(timezoneOffset);
1096
+
1097
+ // Hours, minutes and optional seconds with `:` delimiter
1098
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1099
+ // so this token always has the same output as `XXX`
1100
+ case 'XXXXX':
1101
+ case 'XXX': // Hours and minutes with `:` delimiter
1102
+ default:
1103
+ return formatTimezone(timezoneOffset, ':');
1104
+ }
1105
+ },
1106
+ // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
1107
+ x: function x(date, token, _localize, options) {
1108
+ var originalDate = options._originalDate || date;
1109
+ var timezoneOffset = originalDate.getTimezoneOffset();
1110
+ switch (token) {
1111
+ // Hours and optional minutes
1112
+ case 'x':
1113
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1114
+
1115
+ // Hours, minutes and optional seconds without `:` delimiter
1116
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1117
+ // so this token always has the same output as `xx`
1118
+ case 'xxxx':
1119
+ case 'xx':
1120
+ // Hours and minutes without `:` delimiter
1121
+ return formatTimezone(timezoneOffset);
1122
+
1123
+ // Hours, minutes and optional seconds with `:` delimiter
1124
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1125
+ // so this token always has the same output as `xxx`
1126
+ case 'xxxxx':
1127
+ case 'xxx': // Hours and minutes with `:` delimiter
1128
+ default:
1129
+ return formatTimezone(timezoneOffset, ':');
1130
+ }
1131
+ },
1132
+ // Timezone (GMT)
1133
+ O: function O(date, token, _localize, options) {
1134
+ var originalDate = options._originalDate || date;
1135
+ var timezoneOffset = originalDate.getTimezoneOffset();
1136
+ switch (token) {
1137
+ // Short
1138
+ case 'O':
1139
+ case 'OO':
1140
+ case 'OOO':
1141
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1142
+ // Long
1143
+ case 'OOOO':
1144
+ default:
1145
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1146
+ }
1147
+ },
1148
+ // Timezone (specific non-location)
1149
+ z: function z(date, token, _localize, options) {
1150
+ var originalDate = options._originalDate || date;
1151
+ var timezoneOffset = originalDate.getTimezoneOffset();
1152
+ switch (token) {
1153
+ // Short
1154
+ case 'z':
1155
+ case 'zz':
1156
+ case 'zzz':
1157
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1158
+ // Long
1159
+ case 'zzzz':
1160
+ default:
1161
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1162
+ }
1163
+ },
1164
+ // Seconds timestamp
1165
+ t: function t(date, token, _localize, options) {
1166
+ var originalDate = options._originalDate || date;
1167
+ var timestamp = Math.floor(originalDate.getTime() / 1000);
1168
+ return addLeadingZeros(timestamp, token.length);
1169
+ },
1170
+ // Milliseconds timestamp
1171
+ T: function T(date, token, _localize, options) {
1172
+ var originalDate = options._originalDate || date;
1173
+ var timestamp = originalDate.getTime();
1174
+ return addLeadingZeros(timestamp, token.length);
1175
+ }
1176
+ };
1177
+ function formatTimezoneShort(offset, dirtyDelimiter) {
1178
+ var sign = offset > 0 ? '-' : '+';
1179
+ var absOffset = Math.abs(offset);
1180
+ var hours = Math.floor(absOffset / 60);
1181
+ var minutes = absOffset % 60;
1182
+ if (minutes === 0) {
1183
+ return sign + String(hours);
1184
+ }
1185
+ var delimiter = dirtyDelimiter || '';
1186
+ return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
1187
+ }
1188
+ function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
1189
+ if (offset % 60 === 0) {
1190
+ var sign = offset > 0 ? '-' : '+';
1191
+ return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
1192
+ }
1193
+ return formatTimezone(offset, dirtyDelimiter);
1194
+ }
1195
+ function formatTimezone(offset, dirtyDelimiter) {
1196
+ var delimiter = dirtyDelimiter || '';
1197
+ var sign = offset > 0 ? '-' : '+';
1198
+ var absOffset = Math.abs(offset);
1199
+ var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
1200
+ var minutes = addLeadingZeros(absOffset % 60, 2);
1201
+ return sign + hours + delimiter + minutes;
1202
+ }
1203
+ var formatters$1 = formatters;
1204
+
1205
+ var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
1206
+ switch (pattern) {
1207
+ case 'P':
1208
+ return formatLong.date({
1209
+ width: 'short'
1210
+ });
1211
+ case 'PP':
1212
+ return formatLong.date({
1213
+ width: 'medium'
1214
+ });
1215
+ case 'PPP':
1216
+ return formatLong.date({
1217
+ width: 'long'
1218
+ });
1219
+ case 'PPPP':
1220
+ default:
1221
+ return formatLong.date({
1222
+ width: 'full'
1223
+ });
1224
+ }
1225
+ };
1226
+ var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
1227
+ switch (pattern) {
1228
+ case 'p':
1229
+ return formatLong.time({
1230
+ width: 'short'
1231
+ });
1232
+ case 'pp':
1233
+ return formatLong.time({
1234
+ width: 'medium'
1235
+ });
1236
+ case 'ppp':
1237
+ return formatLong.time({
1238
+ width: 'long'
1239
+ });
1240
+ case 'pppp':
1241
+ default:
1242
+ return formatLong.time({
1243
+ width: 'full'
1244
+ });
1245
+ }
1246
+ };
1247
+ var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
1248
+ var matchResult = pattern.match(/(P+)(p+)?/) || [];
1249
+ var datePattern = matchResult[1];
1250
+ var timePattern = matchResult[2];
1251
+ if (!timePattern) {
1252
+ return dateLongFormatter(pattern, formatLong);
1253
+ }
1254
+ var dateTimeFormat;
1255
+ switch (datePattern) {
1256
+ case 'P':
1257
+ dateTimeFormat = formatLong.dateTime({
1258
+ width: 'short'
1259
+ });
1260
+ break;
1261
+ case 'PP':
1262
+ dateTimeFormat = formatLong.dateTime({
1263
+ width: 'medium'
1264
+ });
1265
+ break;
1266
+ case 'PPP':
1267
+ dateTimeFormat = formatLong.dateTime({
1268
+ width: 'long'
1269
+ });
1270
+ break;
1271
+ case 'PPPP':
1272
+ default:
1273
+ dateTimeFormat = formatLong.dateTime({
1274
+ width: 'full'
1275
+ });
1276
+ break;
1277
+ }
1278
+ return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
1279
+ };
1280
+ var longFormatters = {
1281
+ p: timeLongFormatter,
1282
+ P: dateTimeLongFormatter
1283
+ };
1284
+ var longFormatters$1 = longFormatters;
1285
+
1286
+ /**
1287
+ * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
1288
+ * They usually appear for dates that denote time before the timezones were introduced
1289
+ * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
1290
+ * and GMT+01:00:00 after that date)
1291
+ *
1292
+ * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
1293
+ * which would lead to incorrect calculations.
1294
+ *
1295
+ * This function returns the timezone offset in milliseconds that takes seconds in account.
1296
+ */
1297
+ function getTimezoneOffsetInMilliseconds(date) {
1298
+ var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
1299
+ utcDate.setUTCFullYear(date.getFullYear());
1300
+ return date.getTime() - utcDate.getTime();
1301
+ }
1302
+
1303
+ var protectedDayOfYearTokens = ['D', 'DD'];
1304
+ var protectedWeekYearTokens = ['YY', 'YYYY'];
1305
+ function isProtectedDayOfYearToken(token) {
1306
+ return protectedDayOfYearTokens.indexOf(token) !== -1;
1307
+ }
1308
+ function isProtectedWeekYearToken(token) {
1309
+ return protectedWeekYearTokens.indexOf(token) !== -1;
1310
+ }
1311
+ function throwProtectedError(token, format, input) {
1312
+ if (token === 'YYYY') {
1313
+ throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1314
+ } else if (token === 'YY') {
1315
+ throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1316
+ } else if (token === 'D') {
1317
+ throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1318
+ } else if (token === 'DD') {
1319
+ throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1320
+ }
1321
+ }
1322
+
1323
+ var formatDistanceLocale = {
1324
+ lessThanXSeconds: {
1325
+ one: 'less than a second',
1326
+ other: 'less than {{count}} seconds'
1327
+ },
1328
+ xSeconds: {
1329
+ one: '1 second',
1330
+ other: '{{count}} seconds'
1331
+ },
1332
+ halfAMinute: 'half a minute',
1333
+ lessThanXMinutes: {
1334
+ one: 'less than a minute',
1335
+ other: 'less than {{count}} minutes'
1336
+ },
1337
+ xMinutes: {
1338
+ one: '1 minute',
1339
+ other: '{{count}} minutes'
1340
+ },
1341
+ aboutXHours: {
1342
+ one: 'about 1 hour',
1343
+ other: 'about {{count}} hours'
1344
+ },
1345
+ xHours: {
1346
+ one: '1 hour',
1347
+ other: '{{count}} hours'
1348
+ },
1349
+ xDays: {
1350
+ one: '1 day',
1351
+ other: '{{count}} days'
1352
+ },
1353
+ aboutXWeeks: {
1354
+ one: 'about 1 week',
1355
+ other: 'about {{count}} weeks'
1356
+ },
1357
+ xWeeks: {
1358
+ one: '1 week',
1359
+ other: '{{count}} weeks'
1360
+ },
1361
+ aboutXMonths: {
1362
+ one: 'about 1 month',
1363
+ other: 'about {{count}} months'
1364
+ },
1365
+ xMonths: {
1366
+ one: '1 month',
1367
+ other: '{{count}} months'
1368
+ },
1369
+ aboutXYears: {
1370
+ one: 'about 1 year',
1371
+ other: 'about {{count}} years'
1372
+ },
1373
+ xYears: {
1374
+ one: '1 year',
1375
+ other: '{{count}} years'
1376
+ },
1377
+ overXYears: {
1378
+ one: 'over 1 year',
1379
+ other: 'over {{count}} years'
1380
+ },
1381
+ almostXYears: {
1382
+ one: 'almost 1 year',
1383
+ other: 'almost {{count}} years'
1384
+ }
1385
+ };
1386
+ var formatDistance = function formatDistance(token, count, options) {
1387
+ var result;
1388
+ var tokenValue = formatDistanceLocale[token];
1389
+ if (typeof tokenValue === 'string') {
1390
+ result = tokenValue;
1391
+ } else if (count === 1) {
1392
+ result = tokenValue.one;
1393
+ } else {
1394
+ result = tokenValue.other.replace('{{count}}', count.toString());
1395
+ }
1396
+ if (options !== null && options !== void 0 && options.addSuffix) {
1397
+ if (options.comparison && options.comparison > 0) {
1398
+ return 'in ' + result;
1399
+ } else {
1400
+ return result + ' ago';
1401
+ }
1402
+ }
1403
+ return result;
1404
+ };
1405
+ var formatDistance$1 = formatDistance;
1406
+
1407
+ function buildFormatLongFn(args) {
1408
+ return function () {
1409
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1410
+ // TODO: Remove String()
1411
+ var width = options.width ? String(options.width) : args.defaultWidth;
1412
+ var format = args.formats[width] || args.formats[args.defaultWidth];
1413
+ return format;
1414
+ };
1415
+ }
1416
+
1417
+ var dateFormats = {
1418
+ full: 'EEEE, MMMM do, y',
1419
+ long: 'MMMM do, y',
1420
+ medium: 'MMM d, y',
1421
+ short: 'MM/dd/yyyy'
1422
+ };
1423
+ var timeFormats = {
1424
+ full: 'h:mm:ss a zzzz',
1425
+ long: 'h:mm:ss a z',
1426
+ medium: 'h:mm:ss a',
1427
+ short: 'h:mm a'
1428
+ };
1429
+ var dateTimeFormats = {
1430
+ full: "{{date}} 'at' {{time}}",
1431
+ long: "{{date}} 'at' {{time}}",
1432
+ medium: '{{date}}, {{time}}',
1433
+ short: '{{date}}, {{time}}'
1434
+ };
1435
+ var formatLong = {
1436
+ date: buildFormatLongFn({
1437
+ formats: dateFormats,
1438
+ defaultWidth: 'full'
1439
+ }),
1440
+ time: buildFormatLongFn({
1441
+ formats: timeFormats,
1442
+ defaultWidth: 'full'
1443
+ }),
1444
+ dateTime: buildFormatLongFn({
1445
+ formats: dateTimeFormats,
1446
+ defaultWidth: 'full'
1447
+ })
1448
+ };
1449
+ var formatLong$1 = formatLong;
1450
+
1451
+ var formatRelativeLocale = {
1452
+ lastWeek: "'last' eeee 'at' p",
1453
+ yesterday: "'yesterday at' p",
1454
+ today: "'today at' p",
1455
+ tomorrow: "'tomorrow at' p",
1456
+ nextWeek: "eeee 'at' p",
1457
+ other: 'P'
1458
+ };
1459
+ var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
1460
+ return formatRelativeLocale[token];
1461
+ };
1462
+ var formatRelative$1 = formatRelative;
1463
+
1464
+ function buildLocalizeFn(args) {
1465
+ return function (dirtyIndex, options) {
1466
+ var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
1467
+ var valuesArray;
1468
+ if (context === 'formatting' && args.formattingValues) {
1469
+ var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
1470
+ var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
1471
+ valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
1472
+ } else {
1473
+ var _defaultWidth = args.defaultWidth;
1474
+ var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
1475
+ valuesArray = args.values[_width] || args.values[_defaultWidth];
1476
+ }
1477
+ var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
1478
+ // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
1479
+ return valuesArray[index];
1480
+ };
1481
+ }
1482
+
1483
+ var eraValues = {
1484
+ narrow: ['B', 'A'],
1485
+ abbreviated: ['BC', 'AD'],
1486
+ wide: ['Before Christ', 'Anno Domini']
1487
+ };
1488
+ var quarterValues = {
1489
+ narrow: ['1', '2', '3', '4'],
1490
+ abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
1491
+ wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
1492
+ };
1493
+
1494
+ // Note: in English, the names of days of the week and months are capitalized.
1495
+ // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1496
+ // Generally, formatted dates should look like they are in the middle of a sentence,
1497
+ // e.g. in Spanish language the weekdays and months should be in the lowercase.
1498
+ var monthValues = {
1499
+ narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
1500
+ abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
1501
+ wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
1502
+ };
1503
+ var dayValues = {
1504
+ narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
1505
+ short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
1506
+ abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
1507
+ wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
1508
+ };
1509
+ var dayPeriodValues = {
1510
+ narrow: {
1511
+ am: 'a',
1512
+ pm: 'p',
1513
+ midnight: 'mi',
1514
+ noon: 'n',
1515
+ morning: 'morning',
1516
+ afternoon: 'afternoon',
1517
+ evening: 'evening',
1518
+ night: 'night'
1519
+ },
1520
+ abbreviated: {
1521
+ am: 'AM',
1522
+ pm: 'PM',
1523
+ midnight: 'midnight',
1524
+ noon: 'noon',
1525
+ morning: 'morning',
1526
+ afternoon: 'afternoon',
1527
+ evening: 'evening',
1528
+ night: 'night'
1529
+ },
1530
+ wide: {
1531
+ am: 'a.m.',
1532
+ pm: 'p.m.',
1533
+ midnight: 'midnight',
1534
+ noon: 'noon',
1535
+ morning: 'morning',
1536
+ afternoon: 'afternoon',
1537
+ evening: 'evening',
1538
+ night: 'night'
1539
+ }
1540
+ };
1541
+ var formattingDayPeriodValues = {
1542
+ narrow: {
1543
+ am: 'a',
1544
+ pm: 'p',
1545
+ midnight: 'mi',
1546
+ noon: 'n',
1547
+ morning: 'in the morning',
1548
+ afternoon: 'in the afternoon',
1549
+ evening: 'in the evening',
1550
+ night: 'at night'
1551
+ },
1552
+ abbreviated: {
1553
+ am: 'AM',
1554
+ pm: 'PM',
1555
+ midnight: 'midnight',
1556
+ noon: 'noon',
1557
+ morning: 'in the morning',
1558
+ afternoon: 'in the afternoon',
1559
+ evening: 'in the evening',
1560
+ night: 'at night'
1561
+ },
1562
+ wide: {
1563
+ am: 'a.m.',
1564
+ pm: 'p.m.',
1565
+ midnight: 'midnight',
1566
+ noon: 'noon',
1567
+ morning: 'in the morning',
1568
+ afternoon: 'in the afternoon',
1569
+ evening: 'in the evening',
1570
+ night: 'at night'
1571
+ }
1572
+ };
1573
+ var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
1574
+ var number = Number(dirtyNumber);
1575
+
1576
+ // If ordinal numbers depend on context, for example,
1577
+ // if they are different for different grammatical genders,
1578
+ // use `options.unit`.
1579
+ //
1580
+ // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
1581
+ // 'day', 'hour', 'minute', 'second'.
1582
+
1583
+ var rem100 = number % 100;
1584
+ if (rem100 > 20 || rem100 < 10) {
1585
+ switch (rem100 % 10) {
1586
+ case 1:
1587
+ return number + 'st';
1588
+ case 2:
1589
+ return number + 'nd';
1590
+ case 3:
1591
+ return number + 'rd';
1592
+ }
1593
+ }
1594
+ return number + 'th';
1595
+ };
1596
+ var localize = {
1597
+ ordinalNumber: ordinalNumber,
1598
+ era: buildLocalizeFn({
1599
+ values: eraValues,
1600
+ defaultWidth: 'wide'
1601
+ }),
1602
+ quarter: buildLocalizeFn({
1603
+ values: quarterValues,
1604
+ defaultWidth: 'wide',
1605
+ argumentCallback: function argumentCallback(quarter) {
1606
+ return quarter - 1;
1607
+ }
1608
+ }),
1609
+ month: buildLocalizeFn({
1610
+ values: monthValues,
1611
+ defaultWidth: 'wide'
1612
+ }),
1613
+ day: buildLocalizeFn({
1614
+ values: dayValues,
1615
+ defaultWidth: 'wide'
1616
+ }),
1617
+ dayPeriod: buildLocalizeFn({
1618
+ values: dayPeriodValues,
1619
+ defaultWidth: 'wide',
1620
+ formattingValues: formattingDayPeriodValues,
1621
+ defaultFormattingWidth: 'wide'
1622
+ })
1623
+ };
1624
+ var localize$1 = localize;
1625
+
1626
+ function buildMatchFn(args) {
1627
+ return function (string) {
1628
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1629
+ var width = options.width;
1630
+ var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
1631
+ var matchResult = string.match(matchPattern);
1632
+ if (!matchResult) {
1633
+ return null;
1634
+ }
1635
+ var matchedString = matchResult[0];
1636
+ var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
1637
+ var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
1638
+ return pattern.test(matchedString);
1639
+ }) : findKey(parsePatterns, function (pattern) {
1640
+ return pattern.test(matchedString);
1641
+ });
1642
+ var value;
1643
+ value = args.valueCallback ? args.valueCallback(key) : key;
1644
+ value = options.valueCallback ? options.valueCallback(value) : value;
1645
+ var rest = string.slice(matchedString.length);
1646
+ return {
1647
+ value: value,
1648
+ rest: rest
1649
+ };
1650
+ };
1651
+ }
1652
+ function findKey(object, predicate) {
1653
+ for (var key in object) {
1654
+ if (object.hasOwnProperty(key) && predicate(object[key])) {
1655
+ return key;
1656
+ }
1657
+ }
1658
+ return undefined;
1659
+ }
1660
+ function findIndex(array, predicate) {
1661
+ for (var key = 0; key < array.length; key++) {
1662
+ if (predicate(array[key])) {
1663
+ return key;
1664
+ }
1665
+ }
1666
+ return undefined;
1667
+ }
1668
+
1669
+ function buildMatchPatternFn(args) {
1670
+ return function (string) {
1671
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1672
+ var matchResult = string.match(args.matchPattern);
1673
+ if (!matchResult) return null;
1674
+ var matchedString = matchResult[0];
1675
+ var parseResult = string.match(args.parsePattern);
1676
+ if (!parseResult) return null;
1677
+ var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
1678
+ value = options.valueCallback ? options.valueCallback(value) : value;
1679
+ var rest = string.slice(matchedString.length);
1680
+ return {
1681
+ value: value,
1682
+ rest: rest
1683
+ };
1684
+ };
1685
+ }
1686
+
1687
+ var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
1688
+ var parseOrdinalNumberPattern = /\d+/i;
1689
+ var matchEraPatterns = {
1690
+ narrow: /^(b|a)/i,
1691
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
1692
+ wide: /^(before christ|before common era|anno domini|common era)/i
1693
+ };
1694
+ var parseEraPatterns = {
1695
+ any: [/^b/i, /^(a|c)/i]
1696
+ };
1697
+ var matchQuarterPatterns = {
1698
+ narrow: /^[1234]/i,
1699
+ abbreviated: /^q[1234]/i,
1700
+ wide: /^[1234](th|st|nd|rd)? quarter/i
1701
+ };
1702
+ var parseQuarterPatterns = {
1703
+ any: [/1/i, /2/i, /3/i, /4/i]
1704
+ };
1705
+ var matchMonthPatterns = {
1706
+ narrow: /^[jfmasond]/i,
1707
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
1708
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
1709
+ };
1710
+ var parseMonthPatterns = {
1711
+ narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
1712
+ any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
1713
+ };
1714
+ var matchDayPatterns = {
1715
+ narrow: /^[smtwf]/i,
1716
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
1717
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
1718
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
1719
+ };
1720
+ var parseDayPatterns = {
1721
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
1722
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
1723
+ };
1724
+ var matchDayPeriodPatterns = {
1725
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
1726
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
1727
+ };
1728
+ var parseDayPeriodPatterns = {
1729
+ any: {
1730
+ am: /^a/i,
1731
+ pm: /^p/i,
1732
+ midnight: /^mi/i,
1733
+ noon: /^no/i,
1734
+ morning: /morning/i,
1735
+ afternoon: /afternoon/i,
1736
+ evening: /evening/i,
1737
+ night: /night/i
1738
+ }
1739
+ };
1740
+ var match = {
1741
+ ordinalNumber: buildMatchPatternFn({
1742
+ matchPattern: matchOrdinalNumberPattern,
1743
+ parsePattern: parseOrdinalNumberPattern,
1744
+ valueCallback: function valueCallback(value) {
1745
+ return parseInt(value, 10);
1746
+ }
1747
+ }),
1748
+ era: buildMatchFn({
1749
+ matchPatterns: matchEraPatterns,
1750
+ defaultMatchWidth: 'wide',
1751
+ parsePatterns: parseEraPatterns,
1752
+ defaultParseWidth: 'any'
1753
+ }),
1754
+ quarter: buildMatchFn({
1755
+ matchPatterns: matchQuarterPatterns,
1756
+ defaultMatchWidth: 'wide',
1757
+ parsePatterns: parseQuarterPatterns,
1758
+ defaultParseWidth: 'any',
1759
+ valueCallback: function valueCallback(index) {
1760
+ return index + 1;
1761
+ }
1762
+ }),
1763
+ month: buildMatchFn({
1764
+ matchPatterns: matchMonthPatterns,
1765
+ defaultMatchWidth: 'wide',
1766
+ parsePatterns: parseMonthPatterns,
1767
+ defaultParseWidth: 'any'
1768
+ }),
1769
+ day: buildMatchFn({
1770
+ matchPatterns: matchDayPatterns,
1771
+ defaultMatchWidth: 'wide',
1772
+ parsePatterns: parseDayPatterns,
1773
+ defaultParseWidth: 'any'
1774
+ }),
1775
+ dayPeriod: buildMatchFn({
1776
+ matchPatterns: matchDayPeriodPatterns,
1777
+ defaultMatchWidth: 'any',
1778
+ parsePatterns: parseDayPeriodPatterns,
1779
+ defaultParseWidth: 'any'
1780
+ })
1781
+ };
1782
+ var match$1 = match;
1783
+
1784
+ /**
1785
+ * @type {Locale}
1786
+ * @category Locales
1787
+ * @summary English locale (United States).
1788
+ * @language English
1789
+ * @iso-639-2 eng
1790
+ * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
1791
+ * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
1792
+ */
1793
+ var locale = {
1794
+ code: 'en-US',
1795
+ formatDistance: formatDistance$1,
1796
+ formatLong: formatLong$1,
1797
+ formatRelative: formatRelative$1,
1798
+ localize: localize$1,
1799
+ match: match$1,
1800
+ options: {
1801
+ weekStartsOn: 0 /* Sunday */,
1802
+ firstWeekContainsDate: 1
1803
+ }
1804
+ };
1805
+ var defaultLocale = locale;
1806
+
1807
+ // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
1808
+ // (one of the certain letters followed by `o`)
1809
+ // - (\w)\1* matches any sequences of the same letter
1810
+ // - '' matches two quote characters in a row
1811
+ // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
1812
+ // except a single quote symbol, which ends the sequence.
1813
+ // Two quote characters do not end the sequence.
1814
+ // If there is no matching single quote
1815
+ // then the sequence will continue until the end of the string.
1816
+ // - . matches any single character unmatched by previous parts of the RegExps
1817
+ var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
1818
+
1819
+ // This RegExp catches symbols escaped by quotes, and also
1820
+ // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
1821
+ var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
1822
+ var escapedStringRegExp = /^'([^]*?)'?$/;
1823
+ var doubleQuoteRegExp = /''/g;
1824
+ var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
1825
+
1826
+ /**
1827
+ * @name format
1828
+ * @category Common Helpers
1829
+ * @summary Format the date.
1830
+ *
1831
+ * @description
1832
+ * Return the formatted date string in the given format. The result may vary by locale.
1833
+ *
1834
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
1835
+ * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
1836
+ *
1837
+ * The characters wrapped between two single quotes characters (') are escaped.
1838
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
1839
+ * (see the last example)
1840
+ *
1841
+ * Format of the string is based on Unicode Technical Standard #35:
1842
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
1843
+ * with a few additions (see note 7 below the table).
1844
+ *
1845
+ * Accepted patterns:
1846
+ * | Unit | Pattern | Result examples | Notes |
1847
+ * |---------------------------------|---------|-----------------------------------|-------|
1848
+ * | Era | G..GGG | AD, BC | |
1849
+ * | | GGGG | Anno Domini, Before Christ | 2 |
1850
+ * | | GGGGG | A, B | |
1851
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
1852
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
1853
+ * | | yy | 44, 01, 00, 17 | 5 |
1854
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
1855
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
1856
+ * | | yyyyy | ... | 3,5 |
1857
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
1858
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
1859
+ * | | YY | 44, 01, 00, 17 | 5,8 |
1860
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
1861
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
1862
+ * | | YYYYY | ... | 3,5 |
1863
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
1864
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
1865
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
1866
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
1867
+ * | | RRRRR | ... | 3,5,7 |
1868
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
1869
+ * | | uu | -43, 01, 1900, 2017 | 5 |
1870
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
1871
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
1872
+ * | | uuuuu | ... | 3,5 |
1873
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
1874
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
1875
+ * | | QQ | 01, 02, 03, 04 | |
1876
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
1877
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
1878
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
1879
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
1880
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
1881
+ * | | qq | 01, 02, 03, 04 | |
1882
+ * | | qqq | Q1, Q2, Q3, Q4 | |
1883
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
1884
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
1885
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
1886
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
1887
+ * | | MM | 01, 02, ..., 12 | |
1888
+ * | | MMM | Jan, Feb, ..., Dec | |
1889
+ * | | MMMM | January, February, ..., December | 2 |
1890
+ * | | MMMMM | J, F, ..., D | |
1891
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
1892
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
1893
+ * | | LL | 01, 02, ..., 12 | |
1894
+ * | | LLL | Jan, Feb, ..., Dec | |
1895
+ * | | LLLL | January, February, ..., December | 2 |
1896
+ * | | LLLLL | J, F, ..., D | |
1897
+ * | Local week of year | w | 1, 2, ..., 53 | |
1898
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
1899
+ * | | ww | 01, 02, ..., 53 | |
1900
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
1901
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
1902
+ * | | II | 01, 02, ..., 53 | 7 |
1903
+ * | Day of month | d | 1, 2, ..., 31 | |
1904
+ * | | do | 1st, 2nd, ..., 31st | 7 |
1905
+ * | | dd | 01, 02, ..., 31 | |
1906
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
1907
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
1908
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
1909
+ * | | DDD | 001, 002, ..., 365, 366 | |
1910
+ * | | DDDD | ... | 3 |
1911
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
1912
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
1913
+ * | | EEEEE | M, T, W, T, F, S, S | |
1914
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
1915
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
1916
+ * | | io | 1st, 2nd, ..., 7th | 7 |
1917
+ * | | ii | 01, 02, ..., 07 | 7 |
1918
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
1919
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
1920
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
1921
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
1922
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
1923
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
1924
+ * | | ee | 02, 03, ..., 01 | |
1925
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
1926
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
1927
+ * | | eeeee | M, T, W, T, F, S, S | |
1928
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
1929
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
1930
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
1931
+ * | | cc | 02, 03, ..., 01 | |
1932
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
1933
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
1934
+ * | | ccccc | M, T, W, T, F, S, S | |
1935
+ * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
1936
+ * | AM, PM | a..aa | AM, PM | |
1937
+ * | | aaa | am, pm | |
1938
+ * | | aaaa | a.m., p.m. | 2 |
1939
+ * | | aaaaa | a, p | |
1940
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
1941
+ * | | bbb | am, pm, noon, midnight | |
1942
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
1943
+ * | | bbbbb | a, p, n, mi | |
1944
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
1945
+ * | | BBBB | at night, in the morning, ... | 2 |
1946
+ * | | BBBBB | at night, in the morning, ... | |
1947
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
1948
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
1949
+ * | | hh | 01, 02, ..., 11, 12 | |
1950
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
1951
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
1952
+ * | | HH | 00, 01, 02, ..., 23 | |
1953
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
1954
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
1955
+ * | | KK | 01, 02, ..., 11, 00 | |
1956
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
1957
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
1958
+ * | | kk | 24, 01, 02, ..., 23 | |
1959
+ * | Minute | m | 0, 1, ..., 59 | |
1960
+ * | | mo | 0th, 1st, ..., 59th | 7 |
1961
+ * | | mm | 00, 01, ..., 59 | |
1962
+ * | Second | s | 0, 1, ..., 59 | |
1963
+ * | | so | 0th, 1st, ..., 59th | 7 |
1964
+ * | | ss | 00, 01, ..., 59 | |
1965
+ * | Fraction of second | S | 0, 1, ..., 9 | |
1966
+ * | | SS | 00, 01, ..., 99 | |
1967
+ * | | SSS | 000, 001, ..., 999 | |
1968
+ * | | SSSS | ... | 3 |
1969
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
1970
+ * | | XX | -0800, +0530, Z | |
1971
+ * | | XXX | -08:00, +05:30, Z | |
1972
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
1973
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
1974
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
1975
+ * | | xx | -0800, +0530, +0000 | |
1976
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
1977
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
1978
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
1979
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
1980
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
1981
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
1982
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
1983
+ * | Seconds timestamp | t | 512969520 | 7 |
1984
+ * | | tt | ... | 3,7 |
1985
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
1986
+ * | | TT | ... | 3,7 |
1987
+ * | Long localized date | P | 04/29/1453 | 7 |
1988
+ * | | PP | Apr 29, 1453 | 7 |
1989
+ * | | PPP | April 29th, 1453 | 7 |
1990
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
1991
+ * | Long localized time | p | 12:00 AM | 7 |
1992
+ * | | pp | 12:00:00 AM | 7 |
1993
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
1994
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
1995
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
1996
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
1997
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
1998
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
1999
+ * Notes:
2000
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2001
+ * are the same as "stand-alone" units, but are different in some languages.
2002
+ * "Formatting" units are declined according to the rules of the language
2003
+ * in the context of a date. "Stand-alone" units are always nominative singular:
2004
+ *
2005
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2006
+ *
2007
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2008
+ *
2009
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2010
+ * the single quote characters (see below).
2011
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2012
+ * the output will be the same as default pattern for this unit, usually
2013
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2014
+ * are marked with "2" in the last column of the table.
2015
+ *
2016
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2017
+ *
2018
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2019
+ *
2020
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2021
+ *
2022
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2023
+ *
2024
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2025
+ *
2026
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2027
+ * The output will be padded with zeros to match the length of the pattern.
2028
+ *
2029
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2030
+ *
2031
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2032
+ * These tokens represent the shortest form of the quarter.
2033
+ *
2034
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
2035
+ *
2036
+ * | Year | `y` | `u` |
2037
+ * |------|-----|-----|
2038
+ * | AC 1 | 1 | 1 |
2039
+ * | BC 1 | 1 | 0 |
2040
+ * | BC 2 | 2 | -1 |
2041
+ *
2042
+ * Also `yy` always returns the last two digits of a year,
2043
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2044
+ *
2045
+ * | Year | `yy` | `uu` |
2046
+ * |------|------|------|
2047
+ * | 1 | 01 | 01 |
2048
+ * | 14 | 14 | 14 |
2049
+ * | 376 | 76 | 376 |
2050
+ * | 1453 | 53 | 1453 |
2051
+ *
2052
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2053
+ * except local week-numbering years are dependent on `options.weekStartsOn`
2054
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
2055
+ * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
2056
+ *
2057
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2058
+ * so right now these tokens fall back to GMT timezones.
2059
+ *
2060
+ * 7. These patterns are not in the Unicode Technical Standard #35:
2061
+ * - `i`: ISO day of week
2062
+ * - `I`: ISO week of year
2063
+ * - `R`: ISO week-numbering year
2064
+ * - `t`: seconds timestamp
2065
+ * - `T`: milliseconds timestamp
2066
+ * - `o`: ordinal number modifier
2067
+ * - `P`: long localized date
2068
+ * - `p`: long localized time
2069
+ *
2070
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2071
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2072
+ *
2073
+ * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2074
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2075
+ *
2076
+ * @param {Date|Number} date - the original date
2077
+ * @param {String} format - the string of tokens
2078
+ * @param {Object} [options] - an object with options.
2079
+ * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
2080
+ * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
2081
+ * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
2082
+ * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
2083
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2084
+ * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
2085
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2086
+ * @returns {String} the formatted date string
2087
+ * @throws {TypeError} 2 arguments required
2088
+ * @throws {RangeError} `date` must not be Invalid Date
2089
+ * @throws {RangeError} `options.locale` must contain `localize` property
2090
+ * @throws {RangeError} `options.locale` must contain `formatLong` property
2091
+ * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
2092
+ * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
2093
+ * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2094
+ * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2095
+ * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2096
+ * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2097
+ * @throws {RangeError} format string contains an unescaped latin alphabet character
2098
+ *
2099
+ * @example
2100
+ * // Represent 11 February 2014 in middle-endian format:
2101
+ * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2102
+ * //=> '02/11/2014'
2103
+ *
2104
+ * @example
2105
+ * // Represent 2 July 2014 in Esperanto:
2106
+ * import { eoLocale } from 'date-fns/locale/eo'
2107
+ * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2108
+ * locale: eoLocale
2109
+ * })
2110
+ * //=> '2-a de julio 2014'
2111
+ *
2112
+ * @example
2113
+ * // Escape string by single quote characters:
2114
+ * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2115
+ * //=> "3 o'clock"
2116
+ */
2117
+
2118
+ function format(dirtyDate, dirtyFormatStr, options) {
2119
+ var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
2120
+ requiredArgs(2, arguments);
2121
+ var formatStr = String(dirtyFormatStr);
2122
+ var defaultOptions = getDefaultOptions();
2123
+ var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale;
2124
+ var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
2125
+
2126
+ // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
2127
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
2128
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
2129
+ }
2130
+ var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
2131
+
2132
+ // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
2133
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
2134
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
2135
+ }
2136
+ if (!locale.localize) {
2137
+ throw new RangeError('locale must contain localize property');
2138
+ }
2139
+ if (!locale.formatLong) {
2140
+ throw new RangeError('locale must contain formatLong property');
2141
+ }
2142
+ var originalDate = toDate(dirtyDate);
2143
+ if (!isValid(originalDate)) {
2144
+ throw new RangeError('Invalid time value');
2145
+ }
2146
+
2147
+ // Convert the date in system timezone to the same date in UTC+00:00 timezone.
2148
+ // This ensures that when UTC functions will be implemented, locales will be compatible with them.
2149
+ // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
2150
+ var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
2151
+ var utcDate = subMilliseconds(originalDate, timezoneOffset);
2152
+ var formatterOptions = {
2153
+ firstWeekContainsDate: firstWeekContainsDate,
2154
+ weekStartsOn: weekStartsOn,
2155
+ locale: locale,
2156
+ _originalDate: originalDate
2157
+ };
2158
+ var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
2159
+ var firstCharacter = substring[0];
2160
+ if (firstCharacter === 'p' || firstCharacter === 'P') {
2161
+ var longFormatter = longFormatters$1[firstCharacter];
2162
+ return longFormatter(substring, locale.formatLong);
2163
+ }
2164
+ return substring;
2165
+ }).join('').match(formattingTokensRegExp).map(function (substring) {
2166
+ // Replace two single quote characters with one single quote character
2167
+ if (substring === "''") {
2168
+ return "'";
2169
+ }
2170
+ var firstCharacter = substring[0];
2171
+ if (firstCharacter === "'") {
2172
+ return cleanEscapedString(substring);
2173
+ }
2174
+ var formatter = formatters$1[firstCharacter];
2175
+ if (formatter) {
2176
+ if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
2177
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2178
+ }
2179
+ if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
2180
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2181
+ }
2182
+ return formatter(utcDate, substring, locale.localize, formatterOptions);
2183
+ }
2184
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2185
+ throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
2186
+ }
2187
+ return substring;
2188
+ }).join('');
2189
+ return result;
2190
+ }
2191
+ function cleanEscapedString(input) {
2192
+ var matched = input.match(escapedStringRegExp);
2193
+ if (!matched) {
2194
+ return input;
2195
+ }
2196
+ return matched[1].replace(doubleQuoteRegExp, "'");
2197
+ }
2198
+
2199
+ // 数据格式化
2200
+
2201
+ // 完整时间:yyyy-MM-dd HH:mm:ss
2202
+ function format_date(timestamp, str = "yyyy-MM-dd") {
2203
+ if (!timestamp) return ''
2204
+ try {
2205
+ const num = +timestamp;
2206
+ if (num) {
2207
+ return format(num, str)
2208
+ }
2209
+ return format(new Date(timestamp), str)
2210
+ } catch (error) {
2211
+ return ''
2212
+ }
2213
+ }
2214
+
2215
+ function formatDateMinute(timestamp) {
2216
+ if (!timestamp) return ''
2217
+ try {
2218
+ return format(+timestamp, "yyyy-MM-dd HH:mm")
2219
+ } catch (error) {
2220
+ return ''
2221
+ }
2222
+ }
2223
+
2224
+ // 小数转百分比 数字(会删除小数点后面的0)
2225
+ function format_decimal(number = 0, num = 2, scale = 100) {
2226
+ return +(+number * scale).toFixed(num)
2227
+ }
2228
+
2229
+ // 小数转百分比 字符串(不会删除小数点后面的0)
2230
+ function format_decimal_string(number = 0, num = 2, scale = 100) {
2231
+ return (+number * scale).toFixed(num)
2232
+ }
2233
+
2234
+ // 处理金额
2235
+ function format_money(number = 0, num = 2, scale = 100) {
2236
+ return (+number / scale).toFixed(num)
2237
+ }
2238
+
2239
+ // 创建唯一id
2240
+ function create_guid() {
2241
+ return (
2242
+ (Math.random() * 10000000).toString(16).substring(0, 4) +
2243
+ "-" +
2244
+ new Date().getTime() +
2245
+ "-" +
2246
+ Math.random().toString().substring(2, 7)
2247
+ )
2248
+ }
2249
+
2250
+ // 数字格式
2251
+ function format_number(num) {
2252
+ if (!num) return 0
2253
+ let str = `${num}`;
2254
+ let len = str.length;
2255
+ if (len === 3) {
2256
+ return str
2257
+ }
2258
+ let str2 = "";
2259
+ let max = Math.floor(len / 3);
2260
+ if (len % 3 === 0) {
2261
+ max = max - 1;
2262
+ }
2263
+ for (let i = 0; i < max; i++) {
2264
+ let s = str.slice(len - 3, len);
2265
+ str = str.substring(0, len - 3);
2266
+ str2 = "," + s + str2;
2267
+ len = str.length;
2268
+ }
2269
+ str += str2;
2270
+ return str
2271
+ }
2272
+
2273
+ // 数组转标签
2274
+ function arr_label(arr, props) {
2275
+ props = {
2276
+ label: "label",
2277
+ value: "value",
2278
+ children: "children",
2279
+ re: true,
2280
+ ...props,
2281
+ };
2282
+ const obj = {};
2283
+ function re(arr) {
2284
+ if (arr && arr.length > 0) {
2285
+ for (let item of arr) {
2286
+ obj[item[props.value]] = item[props.label];
2287
+ if (props.re) re(item[props.children]);
2288
+ }
2289
+ }
2290
+ }
2291
+ re(arr);
2292
+ return obj
2293
+ }
2294
+
2295
+ // 数组转对象
2296
+ function arr_obj(arr, props) {
2297
+ props = {
2298
+ value: "value",
2299
+ children: "children",
2300
+ re: true,
2301
+ ...props,
2302
+ };
2303
+ const obj = {};
2304
+ function re(arr) {
2305
+ if (arr && arr.length > 0) {
2306
+ for (let item of arr) {
2307
+ obj[item[props.value]] = item;
2308
+ if (props.re) re(item[props.children]);
2309
+ }
2310
+ }
2311
+ }
2312
+ re(arr);
2313
+ return obj
2314
+ }
2315
+
2316
+ // 复制
2317
+ function copy_content(content) {
2318
+ if (typeof document === 'undefined') {
2319
+ console.warn('copy_content需要在浏览器环境使用');
2320
+ return false
2321
+ }
2322
+ const input = document.createElement("input");
2323
+ input.setAttribute("value", content);
2324
+ document.body.appendChild(input);
2325
+ input.select();
2326
+ const result = document.execCommand("copy");
2327
+ document.body.removeChild(input);
2328
+ return result
2329
+ }
2330
+
2331
+ //计算高度
2332
+ function calculate_height(item, container) {
2333
+ if (typeof document === 'undefined') {
2334
+ return false
2335
+ }
2336
+ const dom = document.getElementById(item);
2337
+ const containerDom = document.getElementById(container);
2338
+ if (dom && containerDom) {
2339
+ const height = dom.offsetHeight;
2340
+ const max_height = containerDom.offsetHeight;
2341
+ return height > max_height
2342
+ }
2343
+ return false
2344
+ }
2345
+
2346
+ // 文字超过8个...
2347
+ function formatTxt(text) {
2348
+ if (!text) return ""
2349
+
2350
+ let trimTetx = text.trim();
2351
+
2352
+ if (trimTetx.length <= 8) {
2353
+ return trimTetx
2354
+ }
2355
+
2356
+ return trimTetx.substring(0, 8) + "..."
2357
+ }
2358
+
2359
+ //设置光标
2360
+ function set_cursor(dom, start = 0, end = 0) {
2361
+ if (typeof window === 'undefined' || !dom) {
2362
+ console.warn('set_cursor需要在浏览器环境使用');
2363
+ return
2364
+ }
2365
+ const selection = window.getSelection();
2366
+ const range = document.createRange();
2367
+ range.setStart(dom, start);
2368
+ range.setEnd(dom, end);
2369
+ selection.removeAllRanges();
2370
+ selection.addRange(range);
2371
+ dom.focus();
2372
+ }
2373
+
2374
+ // 同步setTimeout
2375
+ function sleep(time) {
2376
+ return new Promise((resolve) => setTimeout(resolve, time))
2377
+ }
2378
+
2379
+ function detectZoom() {
2380
+ if (typeof window === 'undefined') {
2381
+ return 1
2382
+ }
2383
+ let ratio = 0;
2384
+ const screen = window.screen;
2385
+ const ua = navigator.userAgent.toLowerCase();
2386
+
2387
+ if (window.devicePixelRatio !== undefined) {
2388
+ ratio = window.devicePixelRatio;
2389
+ } else if (~ua.indexOf('msie')) {
2390
+ if (screen.deviceXDPI && screen.logicalXDPI) {
2391
+ ratio = screen.deviceXDPI / screen.logicalXDPI;
2392
+ }
2393
+ } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
2394
+ ratio = window.outerWidth / window.innerWidth;
2395
+ }
2396
+
2397
+ return +ratio
2398
+ }
2399
+
2400
+ /**
2401
+ * 递归查找树节点
2402
+ * @param {Array} tree 树数据
2403
+ * @param {String} id 节点id值
2404
+ * @param {Object} keyMap 节点字段映射
2405
+ * @returns {Object|Null} 节点对象
2406
+ */
2407
+ function findNodeOfTree(tree, id, keyMap = {}) {
2408
+ const _keyMap = {
2409
+ id: "id",
2410
+ children: "children",
2411
+ ...keyMap,
2412
+ };
2413
+
2414
+ function searchTree(nodes) {
2415
+ for (let node of nodes) {
2416
+ if (node[_keyMap.id] === id) {
2417
+ return node
2418
+ }
2419
+ if (node[_keyMap.children] && node[_keyMap.children].length > 0) {
2420
+ const foundNode = searchTree(node[_keyMap.children]);
2421
+ if (foundNode) {
2422
+ return foundNode
2423
+ }
2424
+ }
2425
+ }
2426
+ return null
2427
+ }
2428
+
2429
+ return searchTree(tree)
2430
+ }
2431
+
2432
+ function copyToClip(content, type = "input") {
2433
+ if (typeof document === 'undefined') {
2434
+ console.warn('copyToClip需要在浏览器环境使用');
2435
+ return false
2436
+ }
2437
+ var aux = document.createElement(type);
2438
+ document.body.appendChild(aux);
2439
+ if (type === "input") {
2440
+ aux.setAttribute("value", content);
2441
+ } else {
2442
+ aux.value = content;
2443
+ }
2444
+ aux.select();
2445
+ const result = document.execCommand("copy");
2446
+ document.body.removeChild(aux);
2447
+ return result
2448
+ }
2449
+
2450
+ function hidePhone(phone) {
2451
+ if (!phone) return ''
2452
+ phone = phone.toString();
2453
+ return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
2454
+ }
2455
+
2456
+ /**
2457
+ * 将字符串中的属于正则表达式的特殊字符,转换成正则表达式中的普通字符
2458
+ */
2459
+ function escapeRegExp(string) {
2460
+ if (!string) {
2461
+ return ''
2462
+ }
2463
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
2464
+ }
2465
+
2466
+ // 基于 Promise 的 validateField 方法,为了校验多个字段时避免回调地狱
2467
+ function validateFieldAsync(prop, form) {
2468
+ return new Promise((resolve, reject) => {
2469
+ form.validateField(prop, (valid) => {
2470
+ if (valid) {
2471
+ reject(new Error(valid));
2472
+ } else {
2473
+ resolve();
2474
+ }
2475
+ });
2476
+ })
2477
+ }
2478
+
2479
+ // 校验手机号
2480
+ function validatePhone(rule, value, callback) {
2481
+ const reg = /^1[3456789]\d{9}$/;
2482
+ if (!value) {
2483
+ return callback(new Error("请输入手机号"))
2484
+ } else if (!reg.test(value)) {
2485
+ return callback(new Error("请输入正确的手机号"))
2486
+ } else {
2487
+ callback();
2488
+ }
2489
+ }
2490
+
2491
+ // 对象是否为空
2492
+ function isEmptyObj(obj) {
2493
+ for (const name in obj) {
2494
+ return false
2495
+ }
2496
+ return true
2497
+ }
2498
+
2499
+ // 只判断两个值对应相等,不包含引用
2500
+ function isEqual(a, b) {
2501
+ const classNameA = Object.prototype.toString.call(a);
2502
+ const classNameB = Object.prototype.toString.call(b);
2503
+ // 如果数据类型不相等,则返回false
2504
+ if (classNameA !== classNameB) {
2505
+ return false
2506
+ } else {
2507
+ // 如果数据类型相等,再根据不同数据类型分别判断
2508
+ if (classNameA === "[object Object]") {
2509
+ for (let key in a) {
2510
+ if (!isEqual(a[key], b[key])) return false
2511
+ }
2512
+ for (let key in b) {
2513
+ if (!isEqual(a[key], b[key])) return false
2514
+ }
2515
+ return true
2516
+ } else if (classNameA === "[object Array]") {
2517
+ if (a.length !== b.length) {
2518
+ return false
2519
+ } else {
2520
+ for (let i = 0, len = a.length; i < len; i++) {
2521
+ if (!isEqual(a[i], b[i])) return false
2522
+ }
2523
+ return true
2524
+ }
2525
+ } else if (classNameA === "[object Function]") {
2526
+ return a.toString() === b.toString()
2527
+ } else {
2528
+ return Object.is(a, b)
2529
+ }
2530
+ }
2531
+ }
2532
+
2533
+ // 是否为空
2534
+ function isEmpty(value) {
2535
+ if (value === undefined || value === null || value === "") {
2536
+ return true
2537
+ }
2538
+ return false
2539
+ }
2540
+
2541
+ function getBrowserInfo() {
2542
+ if (typeof navigator === 'undefined') {
2543
+ return {
2544
+ type: "Unknown",
2545
+ version: "Unknown",
2546
+ }
2547
+ }
2548
+ const userAgent = navigator.userAgent;
2549
+ let browserType = "Unknown";
2550
+ let browserVersion = "Unknown";
2551
+
2552
+ // Check for Firefox
2553
+ if (userAgent.indexOf("Firefox") > -1) {
2554
+ browserType = "Mozilla Firefox";
2555
+ const match = userAgent.match(/Firefox\/(\d+\.\d+)/);
2556
+ browserVersion = match ? match[1] : "Unknown";
2557
+ }
2558
+ // Check for Samsung Browser
2559
+ else if (userAgent.indexOf("SamsungBrowser") > -1) {
2560
+ browserType = "Samsung Internet";
2561
+ const match = userAgent.match(/SamsungBrowser\/(\d+\.\d+)/);
2562
+ browserVersion = match ? match[1] : "Unknown";
2563
+ }
2564
+ // Check for Opera or OPR (Opera based on Chromium)
2565
+ else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
2566
+ browserType = "Opera";
2567
+ const match = userAgent.match(/(Opera|OPR)\/(\d+\.\d+)/);
2568
+ browserVersion = match ? match[2] : "Unknown";
2569
+ }
2570
+ // Check for Internet Explorer
2571
+ else if (userAgent.indexOf("Trident") > -1) {
2572
+ browserType = "Microsoft Internet Explorer";
2573
+ const versionMatch = userAgent.match(/rv:(\d+\.\d+)/);
2574
+ if (versionMatch) {
2575
+ browserVersion = versionMatch[1];
2576
+ }
2577
+ }
2578
+ // Check for Microsoft Edge
2579
+ else if (userAgent.indexOf("Edge") > -1) {
2580
+ browserType = "Microsoft Edge";
2581
+ const match = userAgent.match(/Edge\/(\d+\.\d+)/);
2582
+ browserVersion = match ? match[1] : "Unknown";
2583
+ }
2584
+ // Check for Google Chrome
2585
+ else if (userAgent.indexOf("Chrome") > -1) {
2586
+ browserType = "Google Chrome";
2587
+ const match = userAgent.match(/Chrome\/(\d+\.\d+)/);
2588
+ browserVersion = match ? match[1] : "Unknown";
2589
+ }
2590
+ // Check for Apple Safari
2591
+ else if (userAgent.indexOf("Safari") > -1) {
2592
+ browserType = "Apple Safari";
2593
+ const match = userAgent.match(/Version\/(\d+\.\d+)/);
2594
+ browserVersion = match ? match[1] : "Unknown";
2595
+ }
2596
+
2597
+ return {
2598
+ type: browserType,
2599
+ version: browserVersion,
2600
+ }
2601
+ }
2602
+
2603
+ function isSupported() {
2604
+ if (typeof navigator === 'undefined') {
2605
+ return false
2606
+ }
2607
+ const browserInfo = getBrowserInfo();
2608
+ if (browserInfo.type === "Mozilla Firefox") {
2609
+ return parseFloat(browserInfo.version) > 38
2610
+ }
2611
+ return !!(
2612
+ navigator.mediaDevices &&
2613
+ (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia)
2614
+ )
2615
+ }
2616
+
2617
+ // 校验无意义连续符号
2618
+ function validateMeaninglessConsecutiveSymbols(input) {
2619
+ // 检查是否为空
2620
+ if (input.trim() === '') {
2621
+ return {
2622
+ isValid: false,
2623
+ message: '请输入内容',
2624
+ }
2625
+ }
2626
+ // 检查连续符号(中英文符号)
2627
+ const symbolRegex =
2628
+ /([\-\+\=\*\.\,\;\:\!\@\#\$\%\^\&\_\(\)\[\]\{\}\|\\\/\?\<\>\~\"\'\`\s]|[\u3000-\u303F]|[\uFF00-\uFFEF])\1{6,}/;
2629
+ if (symbolRegex.test(input)) {
2630
+ return {
2631
+ isValid: false,
2632
+ message: '输入无意义内容,请修改',
2633
+ }
2634
+ }
2635
+ // 检查连续数字
2636
+ const digitRegex = /(\d)\1{6,}/;
2637
+ if (digitRegex.test(input)) {
2638
+ return {
2639
+ isValid: false,
2640
+ message: '输入无意义内容,请修改',
2641
+ }
2642
+ }
2643
+ // 检查连续相同文字(中英文)
2644
+ const charRegex = /([\u4e00-\u9fa5a-zA-Z])\1{2,}/;
2645
+ if (charRegex.test(input)) {
2646
+ return {
2647
+ isValid: false,
2648
+ message: '输入无意义内容,请修改',
2649
+ }
2650
+ }
2651
+ return {
2652
+ isValid: true,
2653
+ message: '',
2654
+ }
2655
+ }
2656
+
2657
+ // 数据存储
2658
+ const cache = {
2659
+ data: {},
2660
+ set(key, data) {
2661
+ this.data[key] = data;
2662
+ },
2663
+ get(key) {
2664
+ return this.data[key]
2665
+ },
2666
+ clear(key) {
2667
+ if (key) {
2668
+ delete this.data[key];
2669
+ } else {
2670
+ this.data = {};
2671
+ }
2672
+ }
2673
+ };
2674
+
2675
+ // 建立唯一的key值
2676
+ const buildUniqueUrl = (url, method, params = {}, data = {}) => {
2677
+ const paramStr = (obj) => {
2678
+ if (Object.prototype.toString.call(obj) === '[object Object]') {
2679
+ return JSON.stringify(Object.keys(obj).sort().reduce((result, key) => {
2680
+ result[key] = obj[key];
2681
+ return result
2682
+ }, {}))
2683
+ } else {
2684
+ return JSON.stringify(obj)
2685
+ }
2686
+ };
2687
+ url += `?${paramStr(params)}&${paramStr(data)}&${method}`;
2688
+ return url
2689
+ };
2690
+
2691
+ // 系统标识
2692
+ let system_flag = null;
2693
+
2694
+ function set_system_key(key) {
2695
+ system_flag = key;
2696
+ return system_flag;
2697
+ }
2698
+
2699
+ function get_system_key(key) {
2700
+ if (!system_flag) {
2701
+ console.warn("系统标识未设置,请先调用 set_system_key()");
2702
+ return key;
2703
+ }
2704
+ return `${system_flag}_${key}`;
2705
+ }
2706
+
2707
+ // 用户信息
2708
+ function removeSession(key = "session") {
2709
+ if (typeof window === "undefined" || !window.localStorage) {
2710
+ console.warn("localStorage不可用");
2711
+ return;
2712
+ }
2713
+ localStorage.removeItem(get_system_key(key));
2714
+ }
2715
+
2716
+ function setSession(session, key = "session") {
2717
+ if (typeof window === "undefined" || !window.localStorage) {
2718
+ console.warn("localStorage不可用");
2719
+ return;
2720
+ }
2721
+ localStorage.setItem(get_system_key(key), JSON.stringify(session));
2722
+ }
2723
+
2724
+ function getSession(key = "session") {
2725
+ if (typeof window === "undefined" || !window.localStorage) {
2726
+ console.warn("localStorage不可用");
2727
+ return null;
2728
+ }
2729
+ const value = localStorage.getItem(get_system_key(key));
2730
+ if (value === null || value === undefined || value === "") {
2731
+ return value;
2732
+ } else if (value === "undefined") {
2733
+ return undefined;
2734
+ } else {
2735
+ try {
2736
+ return JSON.parse(value);
2737
+ } catch (e) {
2738
+ console.error("解析session失败:", e);
2739
+ return value;
2740
+ }
2741
+ }
2742
+ }
2743
+
2744
+ // 扩展session中的部分属性,而不是全量替换
2745
+ function extentSession(patch, key = "session") {
2746
+ if (typeof window === "undefined" || !window.localStorage) {
2747
+ console.warn("localStorage不可用");
2748
+ return null;
2749
+ }
2750
+ const prev = getSession(key);
2751
+ if (typeof prev === "object" && prev !== null) {
2752
+ localStorage.setItem(
2753
+ get_system_key(key),
2754
+ JSON.stringify({ ...prev, ...patch })
2755
+ );
2756
+ }
2757
+ return getSession(key);
2758
+ }
2759
+
2760
+ function setSessionStorage(session, key = "collapse") {
2761
+ if (typeof window === "undefined" || !window.sessionStorage) {
2762
+ console.warn("sessionStorage不可用");
2763
+ return;
2764
+ }
2765
+ sessionStorage.setItem(get_system_key(key), JSON.stringify(session));
2766
+ }
2767
+
2768
+ function getSessionStorage(key = "collapse") {
2769
+ if (typeof window === "undefined" || !window.sessionStorage) {
2770
+ console.warn("sessionStorage不可用");
2771
+ return null;
2772
+ }
2773
+ const value = sessionStorage.getItem(get_system_key(key));
2774
+ if (value === null || value === undefined || value === "") {
2775
+ return value;
2776
+ } else if (value === "undefined") {
2777
+ return undefined;
2778
+ } else {
2779
+ try {
2780
+ return JSON.parse(value);
2781
+ } catch (e) {
2782
+ console.error("解析sessionStorage失败:", e);
2783
+ return value;
2784
+ }
2785
+ }
2786
+ }
2787
+
2788
+ function removeSessionStorage(key = "collapse") {
2789
+ if (typeof window === "undefined" || !window.sessionStorage) {
2790
+ console.warn("sessionStorage不可用");
2791
+ return;
2792
+ }
2793
+ sessionStorage.removeItem(get_system_key(key));
2794
+ }
2795
+
2796
+ // 图片地址
2797
+ function getImgURL(url) {
2798
+ if (!url) return ''
2799
+ if (!/^http/g.test(url) && !/^data:image/g.test(url)) {
2800
+ const backendServer = typeof window !== 'undefined' && window.GLOBAL_CONFIG
2801
+ ? window.GLOBAL_CONFIG.backend_server
2802
+ : '';
2803
+ if (backendServer) {
2804
+ url = `${backendServer}/_uploads/files/${url}`;
2805
+ }
2806
+ }
2807
+ return url
2808
+ }
2809
+
2810
+ // 量表图片地址
2811
+ function getGaugeImgUrl(url) {
2812
+ if (!url) return ''
2813
+ if (!/^http/g.test(url) && !/^data:image/g.test(url)) {
2814
+ const backendServer = typeof window !== 'undefined' && window.GLOBAL_CONFIG
2815
+ ? window.GLOBAL_CONFIG.backend_server
2816
+ : '';
2817
+ if (backendServer) {
2818
+ url = `${backendServer}/api/v1/ma/mobile/resource/local/files?file=${url}`;
2819
+ }
2820
+ }
2821
+ return url
2822
+ }
2823
+
2824
+ // 医生头像
2825
+ function doctor_head_img(url) {
2826
+ if (!url) {
2827
+ return './img/doc_defalut_male.jpg'
2828
+ }
2829
+ if (!/^http/g.test(url) && !/^data:image/g.test(url)) {
2830
+ return `https://annetinfo1.oss-cn-shenzhen.aliyuncs.com/${url}`
2831
+ }
2832
+ return url
2833
+ }
2834
+
2835
+ /**
2836
+ * 设备检测工具函数
2837
+ */
2838
+
2839
+ /**
2840
+ * 检测当前设备是否为平板
2841
+ * @returns {boolean} 是否为平板设备
2842
+ */
2843
+ function isTablet() {
2844
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2845
+ return false
2846
+ }
2847
+
2848
+ // 获取用户代理字符串
2849
+ const userAgent = navigator.userAgent.toLowerCase();
2850
+
2851
+ // 检测常见的平板设备标识
2852
+ const tabletPatterns = [
2853
+ /ipad/, // iPad
2854
+ /android.*tablet/, // Android 平板
2855
+ /kindle/, // Kindle
2856
+ /silk/, // Amazon Silk
2857
+ /playbook/, // BlackBerry PlayBook
2858
+ /bb10/, // BlackBerry 10
2859
+ /rim tablet/, // BlackBerry Tablet OS
2860
+ /windows.*touch/, // Windows 平板
2861
+ /tablet/, // 通用平板标识
2862
+ ];
2863
+
2864
+ // 检查用户代理是否匹配平板模式
2865
+ const isTabletByUserAgent = tabletPatterns.some(pattern => pattern.test(userAgent));
2866
+
2867
+ // 检测屏幕尺寸和触摸支持
2868
+ const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
2869
+ const screenWidth = window.screen.width;
2870
+ const screenHeight = window.screen.height;
2871
+ const minDimension = Math.min(screenWidth, screenHeight);
2872
+ const maxDimension = Math.max(screenWidth, screenHeight);
2873
+
2874
+ // 平板设备的典型屏幕尺寸范围
2875
+ const isTabletByScreenSize = (
2876
+ (minDimension >= 600 && minDimension <= 1200) &&
2877
+ (maxDimension >= 800 && maxDimension <= 1600)
2878
+ );
2879
+
2880
+ // 检测是否为移动设备但屏幕较大(可能是平板)
2881
+ const isMobile = /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
2882
+ const isLargeMobile = isMobile && minDimension >= 600;
2883
+
2884
+ // 综合判断:用户代理匹配 或 (屏幕尺寸符合平板特征 且 支持触摸) 或 (大屏移动设备)
2885
+ return isTabletByUserAgent ||
2886
+ (isTabletByScreenSize && hasTouch) ||
2887
+ isLargeMobile
2888
+ }
2889
+
2890
+ /**
2891
+ * 检测当前设备类型
2892
+ * @returns {string} 'desktop' | 'tablet' | 'mobile'
2893
+ */
2894
+ function getDeviceType() {
2895
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2896
+ return 'desktop'
2897
+ }
2898
+
2899
+ if (isTablet()) {
2900
+ return 'tablet'
2901
+ }
2902
+
2903
+ const userAgent = navigator.userAgent.toLowerCase();
2904
+ const isMobile = /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
2905
+
2906
+ return isMobile ? 'mobile' : 'desktop'
2907
+ }
2908
+
2909
+ /**
2910
+ * 检测是否为触摸设备
2911
+ * @returns {boolean} 是否为触摸设备
2912
+ */
2913
+ function isTouchDevice() {
2914
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2915
+ return false
2916
+ }
2917
+ return 'ontouchstart' in window || navigator.maxTouchPoints > 0
2918
+ }
2919
+
2920
+ /**
2921
+ * 获取设备信息
2922
+ * @returns {object} 设备信息对象
2923
+ */
2924
+ function getDeviceInfo() {
2925
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2926
+ return {
2927
+ isTablet: false,
2928
+ deviceType: 'desktop',
2929
+ isTouchDevice: false,
2930
+ userAgent: '',
2931
+ screenWidth: 0,
2932
+ screenHeight: 0,
2933
+ devicePixelRatio: 1,
2934
+ orientation: 'unknown'
2935
+ }
2936
+ }
2937
+
2938
+ return {
2939
+ isTablet: isTablet(),
2940
+ deviceType: getDeviceType(),
2941
+ isTouchDevice: isTouchDevice(),
2942
+ userAgent: navigator.userAgent,
2943
+ screenWidth: window.screen.width,
2944
+ screenHeight: window.screen.height,
2945
+ devicePixelRatio: window.devicePixelRatio || 1,
2946
+ orientation: screen.orientation ? screen.orientation.type : 'unknown'
2947
+ }
2948
+ }
2949
+
2950
+ /* eslint-disable */
2951
+
2952
+ /*
2953
+ 将url的传参参数形式的字符串转化为json对象格式
2954
+
2955
+ let param = 'school=gongda&hobby=skating&number=3'
2956
+ let jsonObj = queryToObj(param)
2957
+
2958
+ console.log(jsonObj)
2959
+ 输出:{
2960
+ school: 'gongda',
2961
+ hobby: 'skaing',
2962
+ number: '3'
2963
+ }
2964
+ */
2965
+ function queryToObj(str) {
2966
+ var theRequest = {};
2967
+ if (str) {
2968
+ var strs = str.includes('&') ? str.split('&') : ('&' + str).split('&');
2969
+ for (let i = 0; i < strs.length; i++) {
2970
+ if (strs[i].includes('=')) {
2971
+ const parts = strs[i].split('=');
2972
+ theRequest[parts[0]] = decodeURIComponent(parts[1] || '');
2973
+ }
2974
+ }
2975
+ }
2976
+ return theRequest
2977
+ }
2978
+
2979
+ /*
2980
+ * 将obj转换成url参数形式
2981
+ * toQueryString({a:1,b:2}) => a=1&b=2
2982
+ *
2983
+ * */
2984
+ function toQueryPair(key, value) {
2985
+ if (typeof value == 'undefined') {
2986
+ return key
2987
+ }
2988
+ return key + '=' + encodeURIComponent(value === null ? '' : String(value))
2989
+ }
2990
+
2991
+ function toQueryString(obj) {
2992
+ var ret = [];
2993
+ for (var key in obj) {
2994
+ key = encodeURIComponent(key);
2995
+ var values = obj[key];
2996
+ if (values && values.constructor == Array) {
2997
+ //数组
2998
+ var queryValues = [];
2999
+ for (var i = 0, len = values.length, value; i < len; i++) {
3000
+ value = values[i];
3001
+ queryValues.push(toQueryPair(key, value));
3002
+ }
3003
+ ret = ret.concat(queryValues);
3004
+ } else {
3005
+ //字符串
3006
+ ret.push(toQueryPair(key, values));
3007
+ }
3008
+ }
3009
+ return ret.join('&')
3010
+ }
3011
+
3012
+ /*
3013
+ 直接取url中的参数转为json(或者不转)
3014
+ 用法1:
3015
+ let para = urlToJson()
3016
+ console.log(para)
3017
+
3018
+ 用法2:
3019
+ let para = urlToJson('https://www.baidu.com?a=1&b=2')
3020
+ console.log(para)
3021
+
3022
+ * */
3023
+ function urlToJson(selfUrl) {
3024
+ if (typeof window === 'undefined') {
3025
+ return { paramStr: '', paramJson: {} }
3026
+ }
3027
+ const url = selfUrl ? selfUrl : window.location.href;
3028
+
3029
+ const reg = /\?.*$/; // 正则取'?后的参数'
3030
+ const urlMatch = url.match(reg);
3031
+
3032
+ // 匹配去掉?的纯参数(正则精髓,贪婪永远匹配最后一个?后的参数)
3033
+ const param = urlMatch && urlMatch.length ? urlMatch[0].replace(/^\?*.*\?/, '') : '';
3034
+
3035
+ const output = {
3036
+ paramStr: param,
3037
+ paramJson: queryToObj(param)
3038
+ };
3039
+
3040
+ return output
3041
+ }
3042
+
3043
+ /*
3044
+ 直接取url中的某个参数
3045
+ 用法:
3046
+ let deviceType = getQueryString('deviceType')
3047
+ console.log(deviceType)
3048
+
3049
+ * */
3050
+ function getQueryString(name, url) {
3051
+ if (typeof window === 'undefined') {
3052
+ return ''
3053
+ }
3054
+ url = url || window.location.href;
3055
+ var str = url.match(new RegExp('([?&#])' + name.replace('#', '') + '=([^#&?]*)', 'gi'));
3056
+ return str ? decodeURIComponent(str[0].split('=')[1]) : ''
3057
+ }
3058
+
3059
+ /*
3060
+ 更改url中的某个参数,返回更改后的最终带参数url
3061
+ 参数解析:
3062
+ json: 更改参数的json对象
3063
+ originUrl:预置的网站地址
3064
+
3065
+ 用法一:
3066
+ let resultUrl = setUrl({id: 1, name: '测试页面'})
3067
+ console.log(resultUrl) // 输出:https://********.html?id=1&name=测试页面
3068
+
3069
+ 用法二:
3070
+ let resultUrl = setUrl({id: 3, name: '哈哈哈'}, 'https://www.baidu.com')
3071
+ console.log(resultUrl) // 输出:https://www.baidu.com?id=3&name=哈哈哈
3072
+
3073
+ * */
3074
+ function setUrl(json, originUrl = '') {
3075
+ if (typeof window === 'undefined') {
3076
+ return ''
3077
+ }
3078
+ let paramJson = urlToJson().paramJson;
3079
+ // 新的参数
3080
+ let newJson = {
3081
+ ...paramJson,
3082
+ ...json
3083
+ };
3084
+
3085
+ // 参数对象 =》get参数
3086
+ let paramStr = toQueryString(newJson);
3087
+
3088
+ // url的origin + pathname
3089
+ let oPath = originUrl ? originUrl : window.location.origin + window.location.pathname;
3090
+
3091
+ let resultUrl = oPath + '?' + paramStr;
3092
+ return resultUrl
3093
+ }
3094
+
3095
+ // url参数(兼容旧API)
3096
+ function get_url_params(url) {
3097
+ if (typeof window === 'undefined') {
3098
+ return {}
3099
+ }
3100
+ const targetUrl = url || window.location.href;
3101
+ return urlToJson(targetUrl).paramJson
3102
+ }
3103
+
3104
+ function convertMilliseconds(ms, secondsTo2decimal = false) {
3105
+ if (!ms) return "";
3106
+
3107
+ const hours = Math.floor(ms / 3600000); // 计算小时
3108
+ const minutes = Math.floor((ms % 3600000) / 60000); // 计算分钟
3109
+ let seconds = 0;
3110
+ if (secondsTo2decimal) {
3111
+ seconds = parseFloat(((ms % 60000) / 1000).toFixed(2));
3112
+ } else {
3113
+ seconds = Math.floor((ms % 60000) / 1000); // 计算秒数
3114
+ }
3115
+
3116
+ return {
3117
+ hours,
3118
+ minutes,
3119
+ seconds,
3120
+ };
3121
+ }
3122
+
3123
+ const myDebounce = function (fn, time = 600) {
3124
+ let timerId = "";
3125
+ return function (...arg) {
3126
+ timerId && clearTimeout(timerId);
3127
+ timerId = setTimeout(() => {
3128
+ fn && fn.call(this, ...arg);
3129
+ }, time);
3130
+ };
3131
+ };
3132
+
3133
+ const mapStringifyReplacer = function (key, value) {
3134
+ if (value instanceof Map) {
3135
+ return {
3136
+ dataType: "Map",
3137
+ value: Array.from(value.entries()),
3138
+ };
3139
+ } else {
3140
+ return value;
3141
+ }
3142
+ };
3143
+
3144
+ const mapParseReviver = function (key, value) {
3145
+ if (typeof value === "object" && value !== null) {
3146
+ if (value.dataType === "Map") {
3147
+ return new Map(value.value);
3148
+ }
3149
+ }
3150
+ return value;
3151
+ };
3152
+
3153
+ function getHalfYearAgoToday(reduce = 12) {
3154
+ const today = new Date().setHours(0, 0, 0, 0);
3155
+ const currentMonth = new Date().getMonth();
3156
+ return new Date(today).setMonth(currentMonth - reduce);
3157
+ }
3158
+
3159
+ // 文件下载助手
3160
+ const fileDownloadHelper = {
3161
+ /**
3162
+ * 下载文件
3163
+ * @param {Blob} blob - 文件Blob对象
3164
+ * @param {string} filename - 下载文件名
3165
+ */
3166
+ download(blob, filename) {
3167
+ if (typeof window === "undefined") {
3168
+ console.warn("fileDownloadHelper.download只能在浏览器环境使用");
3169
+ return;
3170
+ }
3171
+ const url = window.URL.createObjectURL(blob);
3172
+ const link = document.createElement("a");
3173
+ link.href = url;
3174
+ link.setAttribute("download", filename);
3175
+ document.body.appendChild(link);
3176
+ link.click();
3177
+ window.URL.revokeObjectURL(url);
3178
+ document.body.removeChild(link);
3179
+ },
3180
+
3181
+ /**
3182
+ * 从响应头获取文件名
3183
+ * @param {Object} headers - 响应头
3184
+ * @param {string} defaultName - 默认文件名
3185
+ * @returns {string} 文件名
3186
+ */
3187
+ getFilenameFromHeaders(headers, defaultName) {
3188
+ const contentDisposition = headers["content-disposition"];
3189
+ if (!contentDisposition) return defaultName;
3190
+
3191
+ const filenameMatch = contentDisposition.match(/filename=(.+)/);
3192
+ return filenameMatch && filenameMatch.length > 1
3193
+ ? decodeURIComponent(filenameMatch[1]).replace(/['"]/g, "")
3194
+ : defaultName;
3195
+ },
3196
+ };
3197
+
3198
+ /**
3199
+ * 复制文本到剪贴板
3200
+ * @param {string} text - 要复制的文本
3201
+ * @returns {Promise<boolean>} - 返回一个Promise,复制成功返回true,失败返回false
3202
+ */
3203
+ async function copyText(text) {
3204
+ if (typeof window === "undefined") {
3205
+ console.warn("copyText只能在浏览器环境使用");
3206
+ return false;
3207
+ }
3208
+
3209
+ try {
3210
+ // 优先使用现代的Clipboard API
3211
+ if (navigator.clipboard && window.isSecureContext) {
3212
+ await navigator.clipboard.writeText(text);
3213
+ return true;
3214
+ }
3215
+
3216
+ // 降级方案:使用传统的document.execCommand方法
3217
+ const textArea = document.createElement("textarea");
3218
+ textArea.value = text;
3219
+
3220
+ // 防止页面滚动
3221
+ textArea.style.position = "fixed";
3222
+ textArea.style.left = "-999999px";
3223
+ textArea.style.top = "-999999px";
3224
+
3225
+ document.body.appendChild(textArea);
3226
+ textArea.focus();
3227
+ textArea.select();
3228
+
3229
+ try {
3230
+ const successful = document.execCommand("copy");
3231
+ document.body.removeChild(textArea);
3232
+ return successful;
3233
+ } catch (err) {
3234
+ document.body.removeChild(textArea);
3235
+ return false;
3236
+ }
3237
+ } catch (err) {
3238
+ return false;
3239
+ }
3240
+ }
3241
+
3242
+ // 防抖(兼容旧API)
3243
+ function debounce(fn, delay = 200) {
3244
+ let timeout = null;
3245
+ return function () {
3246
+ let context = this;
3247
+ let args = arguments;
3248
+ clearTimeout(timeout);
3249
+ timeout = setTimeout(() => {
3250
+ fn.apply(context, args);
3251
+ }, delay);
3252
+ };
3253
+ }
3254
+
3255
+ // 节流
3256
+ const throttle = (fn, delay = 100) => {
3257
+ let timer = null;
3258
+ let start_time = Date.now();
3259
+ return function (...args) {
3260
+ const current_time = Date.now();
3261
+ const diff = delay - (current_time - start_time);
3262
+ if (timer) clearTimeout(timer);
3263
+ if (diff <= 0) {
3264
+ fn.apply(this, args);
3265
+ start_time = Date.now();
3266
+ } else {
3267
+ timer = setTimeout(() => {
3268
+ fn.apply(this, args);
3269
+ }, diff);
3270
+ }
3271
+ };
3272
+ };
3273
+
3274
+ const uuid = function () {
3275
+ let random;
3276
+
3277
+ try {
3278
+ if (typeof window !== 'undefined' && window.crypto) {
3279
+ const arr = new Uint32Array(1);
3280
+ // https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
3281
+ window.crypto.getRandomValues(arr);
3282
+ random = arr[0] & 2147483647;
3283
+ } else {
3284
+ random = Math.floor(Math.random() * 2147483648);
3285
+ }
3286
+ } catch (b) {
3287
+ random = Math.floor(Math.random() * 2147483648);
3288
+ }
3289
+
3290
+ return random.toString(36)
3291
+ };
3292
+
3293
+ const uuidLong = function () {
3294
+ return `${uuid()}${uuid()}${uuid()}`
3295
+ };
3296
+
3297
+ function baseGet(object, path) {
3298
+ path = castPath(path);
3299
+
3300
+ var index = 0,
3301
+ length = path.length;
3302
+
3303
+ while (object != null && index < length) {
3304
+ object = object[path[index++]];
3305
+ }
3306
+ return (index && index == length) ? object : undefined
3307
+ }
3308
+
3309
+ function castPath(value, object) {
3310
+ if (Array.isArray(value)) {
3311
+ return value
3312
+ }
3313
+ return stringToPath(String(value))
3314
+ }
3315
+
3316
+ function stringToPath(string) {
3317
+ var result = [];
3318
+ if (string.charCodeAt(0) === 46 /* . */) {
3319
+ result.push('');
3320
+ }
3321
+ string.replace(/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, function(match, number, quote, subString) {
3322
+ result.push(quote ? subString.replace(/\\(\\)?/g, '$1') : (number || match));
3323
+ });
3324
+ return result
3325
+ }
3326
+
3327
+ function get(object, path, defaultValue) {
3328
+ var result = object == null ? undefined : baseGet(object, path);
3329
+ return result === undefined ? defaultValue : result
3330
+ }
3331
+
3332
+ // 防止重复请求
3333
+ var index = (options = {}) =>
3334
+ async (config) => {
3335
+ const defaultOptions = {
3336
+ time: 0, // 设置为0,不清除缓存
3337
+ ...options,
3338
+ };
3339
+ const index = buildUniqueUrl(
3340
+ config.url,
3341
+ config.method,
3342
+ config.params,
3343
+ config.data
3344
+ );
3345
+ let responsePromise = cache.get(index);
3346
+ if (!responsePromise) {
3347
+ responsePromise = (async () => {
3348
+ try {
3349
+ // 需要确保axios可用,这里假设axios已经通过其他方式引入
3350
+ let axios = null;
3351
+ if (typeof window !== "undefined" && window.axios) {
3352
+ axios = window.axios;
3353
+ } else if (typeof require !== "undefined") {
3354
+ try {
3355
+ axios = require("axios");
3356
+ } catch (e) {
3357
+ // ignore
3358
+ }
3359
+ }
3360
+
3361
+ if (axios && axios.defaults && axios.defaults.adapter) {
3362
+ const response = await axios.defaults.adapter(config);
3363
+ return Promise.resolve(response);
3364
+ } else {
3365
+ throw new Error("axios未找到,请确保已安装axios");
3366
+ }
3367
+ } catch (reason) {
3368
+ cache.clear(index);
3369
+ return Promise.reject(reason);
3370
+ }
3371
+ })();
3372
+ cache.set(index, responsePromise);
3373
+ if (defaultOptions.time !== 0) {
3374
+ setTimeout(() => {
3375
+ cache.clear(index);
3376
+ }, defaultOptions.time);
3377
+ }
3378
+ }
3379
+ return responsePromise.then((data) => JSON.parse(JSON.stringify(data))); // 为防止数据源污染
3380
+ };
3381
+
3382
+ exports.arr_label = arr_label;
3383
+ exports.arr_obj = arr_obj;
3384
+ exports.buildUniqueUrl = buildUniqueUrl;
3385
+ exports.cache = cache;
3386
+ exports.calculate_height = calculate_height;
3387
+ exports.convertMilliseconds = convertMilliseconds;
3388
+ exports.copyText = copyText;
3389
+ exports.copyToClip = copyToClip;
3390
+ exports.copy_content = copy_content;
3391
+ exports.create_guid = create_guid;
3392
+ exports.debounce = debounce;
3393
+ exports.defaultAdapter = index;
3394
+ exports.detectZoom = detectZoom;
3395
+ exports.doctor_head_img = doctor_head_img;
3396
+ exports.escapeRegExp = escapeRegExp;
3397
+ exports.extentSession = extentSession;
3398
+ exports.fileDownloadHelper = fileDownloadHelper;
3399
+ exports.findNodeOfTree = findNodeOfTree;
3400
+ exports.formatDateMinute = formatDateMinute;
3401
+ exports.formatTxt = formatTxt;
3402
+ exports.format_date = format_date;
3403
+ exports.format_decimal = format_decimal;
3404
+ exports.format_decimal_string = format_decimal_string;
3405
+ exports.format_money = format_money;
3406
+ exports.format_number = format_number;
3407
+ exports.get = get;
3408
+ exports.getBrowserInfo = getBrowserInfo;
3409
+ exports.getDeviceInfo = getDeviceInfo;
3410
+ exports.getDeviceType = getDeviceType;
3411
+ exports.getGaugeImgUrl = getGaugeImgUrl;
3412
+ exports.getHalfYearAgoToday = getHalfYearAgoToday;
3413
+ exports.getImgURL = getImgURL;
3414
+ exports.getQueryString = getQueryString;
3415
+ exports.getSession = getSession;
3416
+ exports.getSessionStorage = getSessionStorage;
3417
+ exports.get_system_key = get_system_key;
3418
+ exports.get_url_params = get_url_params;
3419
+ exports.hidePhone = hidePhone;
3420
+ exports.isEmpty = isEmpty;
3421
+ exports.isEmptyObj = isEmptyObj;
3422
+ exports.isEqual = isEqual;
3423
+ exports.isSupported = isSupported;
3424
+ exports.isTablet = isTablet;
3425
+ exports.isTouchDevice = isTouchDevice;
3426
+ exports.mapParseReviver = mapParseReviver;
3427
+ exports.mapStringifyReplacer = mapStringifyReplacer;
3428
+ exports.myDebounce = myDebounce;
3429
+ exports.queryToObj = queryToObj;
3430
+ exports.removeSession = removeSession;
3431
+ exports.removeSessionStorage = removeSessionStorage;
3432
+ exports.setSession = setSession;
3433
+ exports.setSessionStorage = setSessionStorage;
3434
+ exports.setUrl = setUrl;
3435
+ exports.set_cursor = set_cursor;
3436
+ exports.set_system_key = set_system_key;
3437
+ exports.sleep = sleep;
3438
+ exports.throttle = throttle;
3439
+ exports.toQueryString = toQueryString;
3440
+ exports.urlToJson = urlToJson;
3441
+ exports.uuid = uuid;
3442
+ exports.uuidLong = uuidLong;
3443
+ exports.validateFieldAsync = validateFieldAsync;
3444
+ exports.validateMeaninglessConsecutiveSymbols = validateMeaninglessConsecutiveSymbols;
3445
+ exports.validatePhone = validatePhone;