@justifi/webcomponents 0.0.9 → 0.0.11

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.
@@ -1,4294 +0,0 @@
1
- import { r as registerInstance, c as createEvent, h, H as Host } from './index-e279d85e.js';
2
-
3
- const BankAccountForm = class {
4
- constructor(hostRef) {
5
- registerInstance(this, hostRef);
6
- this.bankAccountFormReady = createEvent(this, "bankAccountFormReady", 7);
7
- this.bankAccountFormChange = createEvent(this, "bankAccountFormChange", 7);
8
- this.bankAccountFormBlur = createEvent(this, "bankAccountFormBlur", 7);
9
- this.bankAccountFormTokenize = createEvent(this, "bankAccountFormTokenize", 7);
10
- this.iframeOrigin = undefined;
11
- }
12
- readyHandler(event) {
13
- this.bankAccountFormReady.emit(event);
14
- }
15
- changeHandler(event) {
16
- this.bankAccountFormChange.emit(event);
17
- }
18
- blurHandler(event) {
19
- this.bankAccountFormBlur.emit(event);
20
- }
21
- tokenizeHandler(event) {
22
- this.bankAccountFormTokenize.emit(event);
23
- }
24
- async tokenize(...args) {
25
- if (!this.childRef) {
26
- throw new Error('Cannot call tokenize');
27
- }
28
- return this.childRef.tokenize(...args);
29
- }
30
- render() {
31
- return (h("justifi-payment-method-form", { ref: el => {
32
- if (el) {
33
- this.childRef = el;
34
- }
35
- }, "iframe-origin": this.iframeOrigin || 'https://js.justifi.ai/bank-account', "payment-method-form-ready": this.bankAccountFormReady, "payment-method-form-change": this.bankAccountFormChange, "payment-method-form-blur": this.bankAccountFormBlur, "payment-method-form-tokenize": this.bankAccountFormTokenize }));
36
- }
37
- };
38
-
39
- const cardFormCss = "justifi-card-form iframe{height:55px}";
40
-
41
- const CardForm = class {
42
- constructor(hostRef) {
43
- registerInstance(this, hostRef);
44
- this.cardFormReady = createEvent(this, "cardFormReady", 7);
45
- this.cardFormChange = createEvent(this, "cardFormChange", 7);
46
- this.cardFormBlur = createEvent(this, "cardFormBlur", 7);
47
- this.cardFormTokenize = createEvent(this, "cardFormTokenize", 7);
48
- this.iframeOrigin = undefined;
49
- }
50
- async tokenize(...args) {
51
- if (!this.childRef) {
52
- throw new Error('Cannot call tokenize');
53
- }
54
- return this.childRef.tokenize(...args);
55
- }
56
- render() {
57
- return (h("justifi-payment-method-form", { ref: el => {
58
- if (el) {
59
- this.childRef = el;
60
- }
61
- }, "iframe-origin": this.iframeOrigin || 'https://js.justifi.ai/card', "payment-method-form-ready": this.cardFormReady, "payment-method-form-change": this.cardFormChange, "payment-method-form-blur": this.cardFormBlur, "payment-method-form-tokenize": this.cardFormTokenize }));
62
- }
63
- };
64
- CardForm.style = cardFormCss;
65
-
66
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
67
- // require the crypto API and do not support built-in fallback to lower quality random number
68
- // generators (like Math.random()).
69
- let getRandomValues;
70
- const rnds8 = new Uint8Array(16);
71
- function rng() {
72
- // lazy load so that environments that need to polyfill have a chance to do so
73
- if (!getRandomValues) {
74
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
75
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
76
-
77
- if (!getRandomValues) {
78
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
79
- }
80
- }
81
-
82
- return getRandomValues(rnds8);
83
- }
84
-
85
- /**
86
- * Convert array of 16 byte values to UUID string format of the form:
87
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
88
- */
89
-
90
- const byteToHex = [];
91
-
92
- for (let i = 0; i < 256; ++i) {
93
- byteToHex.push((i + 0x100).toString(16).slice(1));
94
- }
95
-
96
- function unsafeStringify(arr, offset = 0) {
97
- // Note: Be careful editing this code! It's been tuned for performance
98
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
99
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
100
- }
101
-
102
- const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
103
- const native = {
104
- randomUUID
105
- };
106
-
107
- function v4(options, buf, offset) {
108
- if (native.randomUUID && !buf && !options) {
109
- return native.randomUUID();
110
- }
111
-
112
- options = options || {};
113
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
114
-
115
- rnds[6] = rnds[6] & 0x0f | 0x40;
116
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
117
-
118
- if (buf) {
119
- offset = offset || 0;
120
-
121
- for (let i = 0; i < 16; ++i) {
122
- buf[offset + i] = rnds[i];
123
- }
124
-
125
- return buf;
126
- }
127
-
128
- return unsafeStringify(rnds);
129
- }
130
-
131
- const Api = (authToken) => {
132
- const apiOrigin = 'http://localhost:3000';
133
- async function getAuthorizationHeader() {
134
- return {
135
- Authorization: `Bearer ${authToken}`,
136
- 'Idempotency-Key': v4(),
137
- 'Content-Type': 'application/json'
138
- };
139
- }
140
- async function makeRequest(endpoint, method, params, body, signal) {
141
- const url = `${apiOrigin}/v1/${endpoint}`;
142
- const requestUrl = params ? `${url}?${new URLSearchParams(params)}` : url;
143
- const response = await fetch(requestUrl, {
144
- method: method,
145
- headers: await getAuthorizationHeader(),
146
- body: body,
147
- signal: signal
148
- });
149
- if (response) {
150
- return response.status === 204 ? {} : response.json();
151
- }
152
- handleError(requestUrl);
153
- }
154
- async function get(endpoint, params, signal) {
155
- return makeRequest(endpoint, 'GET', params, null, signal);
156
- }
157
- async function post(endpoint, body, params, signal) {
158
- return makeRequest(endpoint, 'POST', params, body, signal);
159
- }
160
- async function patch(endpoint, body, params, signal) {
161
- return makeRequest(endpoint, 'PATCH', params, body, signal);
162
- }
163
- async function destroy(endpoint, params, signal) {
164
- return makeRequest(endpoint, 'DELETE', params, null, signal);
165
- }
166
- return { get, post, patch, destroy };
167
- };
168
- function handleError(requestUrl) {
169
- console.error(`Error fetching from ${requestUrl}`);
170
- }
171
-
172
- var CaptureStrategy;
173
- (function (CaptureStrategy) {
174
- CaptureStrategy["automatic"] = "automatic";
175
- CaptureStrategy["manual"] = "manual";
176
- })(CaptureStrategy || (CaptureStrategy = {}));
177
- var PaymentMethodTypes;
178
- (function (PaymentMethodTypes) {
179
- PaymentMethodTypes["card"] = "card";
180
- PaymentMethodTypes["bankAccount"] = "bank_account";
181
- })(PaymentMethodTypes || (PaymentMethodTypes = {}));
182
- var PaymentStatuses;
183
- (function (PaymentStatuses) {
184
- PaymentStatuses["pending"] = "pending";
185
- PaymentStatuses["authorized"] = "authorized";
186
- PaymentStatuses["succeeded"] = "succeeded";
187
- PaymentStatuses["failed"] = "failed";
188
- PaymentStatuses["disputed"] = "disputed";
189
- PaymentStatuses["fully_refunded"] = "fully_refunded";
190
- PaymentStatuses["partially_refunded"] = "partially_refunded";
191
- })(PaymentStatuses || (PaymentStatuses = {}));
192
- var PaymentDisputedStatuses;
193
- (function (PaymentDisputedStatuses) {
194
- // if a dispute is 'won', we don't show a dispute status, just general status
195
- PaymentDisputedStatuses["lost"] = "lost";
196
- PaymentDisputedStatuses["open"] = "open";
197
- })(PaymentDisputedStatuses || (PaymentDisputedStatuses = {}));
198
- class Payment {
199
- constructor(payment) {
200
- this.id = payment.id;
201
- this.account_id = payment.account_id;
202
- this.amount = payment.amount;
203
- this.amount_disputed = payment.amount_disputed;
204
- this.amount_refundable = payment.amount_refundable;
205
- this.amount_refunded = payment.amount_refunded;
206
- this.balance = payment.balance;
207
- this.captured = payment.captured;
208
- this.capture_strategy = payment.capture_strategy;
209
- this.currency = payment.currency;
210
- this.description = payment.description;
211
- this.disputed = payment.disputed;
212
- this.disputes = payment.disputes;
213
- this.error_code = payment.error_code;
214
- this.error_description = payment.error_description;
215
- this.fee_amount = payment.fee_amount;
216
- this.is_test = payment.is_test;
217
- this.metadata = payment.metadata;
218
- this.payment_method = payment.payment_method;
219
- this.payment_intent_id = payment.payment_intent_id;
220
- this.refunded = payment.refunded;
221
- this.status = payment.status;
222
- this.created_at = payment.created_at;
223
- this.updated_at = payment.updated_at;
224
- }
225
- get disputedStatus() {
226
- const lost = this.disputes.some((dispute) => dispute.status === PaymentDisputedStatuses.lost);
227
- // if a dispute is 'won', we don't show a dispute status, just general status
228
- if (!this.disputed) {
229
- return null;
230
- }
231
- else if (lost) {
232
- return PaymentDisputedStatuses.lost;
233
- }
234
- else {
235
- return PaymentDisputedStatuses.open;
236
- }
237
- }
238
- }
239
-
240
- function toInteger(dirtyNumber) {
241
- if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
242
- return NaN;
243
- }
244
-
245
- var number = Number(dirtyNumber);
246
-
247
- if (isNaN(number)) {
248
- return number;
249
- }
250
-
251
- return number < 0 ? Math.ceil(number) : Math.floor(number);
252
- }
253
-
254
- function requiredArgs(required, args) {
255
- if (args.length < required) {
256
- throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
257
- }
258
- }
259
-
260
- function _typeof$2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }
261
- /**
262
- * @name toDate
263
- * @category Common Helpers
264
- * @summary Convert the given argument to an instance of Date.
265
- *
266
- * @description
267
- * Convert the given argument to an instance of Date.
268
- *
269
- * If the argument is an instance of Date, the function returns its clone.
270
- *
271
- * If the argument is a number, it is treated as a timestamp.
272
- *
273
- * If the argument is none of the above, the function returns Invalid Date.
274
- *
275
- * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
276
- *
277
- * @param {Date|Number} argument - the value to convert
278
- * @returns {Date} the parsed date in the local time zone
279
- * @throws {TypeError} 1 argument required
280
- *
281
- * @example
282
- * // Clone the date:
283
- * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
284
- * //=> Tue Feb 11 2014 11:30:30
285
- *
286
- * @example
287
- * // Convert the timestamp to date:
288
- * const result = toDate(1392098430000)
289
- * //=> Tue Feb 11 2014 11:30:30
290
- */
291
-
292
- function toDate(argument) {
293
- requiredArgs(1, arguments);
294
- var argStr = Object.prototype.toString.call(argument); // Clone the date
295
-
296
- if (argument instanceof Date || _typeof$2(argument) === 'object' && argStr === '[object Date]') {
297
- // Prevent the date to lose the milliseconds when passed to new Date() in IE10
298
- return new Date(argument.getTime());
299
- } else if (typeof argument === 'number' || argStr === '[object Number]') {
300
- return new Date(argument);
301
- } else {
302
- if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
303
- // eslint-disable-next-line no-console
304
- 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"); // eslint-disable-next-line no-console
305
-
306
- console.warn(new Error().stack);
307
- }
308
-
309
- return new Date(NaN);
310
- }
311
- }
312
-
313
- /**
314
- * @name addMilliseconds
315
- * @category Millisecond Helpers
316
- * @summary Add the specified number of milliseconds to the given date.
317
- *
318
- * @description
319
- * Add the specified number of milliseconds to the given date.
320
- *
321
- * @param {Date|Number} date - the date to be changed
322
- * @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`.
323
- * @returns {Date} the new date with the milliseconds added
324
- * @throws {TypeError} 2 arguments required
325
- *
326
- * @example
327
- * // Add 750 milliseconds to 10 July 2014 12:45:30.000:
328
- * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
329
- * //=> Thu Jul 10 2014 12:45:30.750
330
- */
331
-
332
- function addMilliseconds(dirtyDate, dirtyAmount) {
333
- requiredArgs(2, arguments);
334
- var timestamp = toDate(dirtyDate).getTime();
335
- var amount = toInteger(dirtyAmount);
336
- return new Date(timestamp + amount);
337
- }
338
-
339
- var defaultOptions = {};
340
- function getDefaultOptions() {
341
- return defaultOptions;
342
- }
343
-
344
- /**
345
- * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
346
- * They usually appear for dates that denote time before the timezones were introduced
347
- * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
348
- * and GMT+01:00:00 after that date)
349
- *
350
- * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
351
- * which would lead to incorrect calculations.
352
- *
353
- * This function returns the timezone offset in milliseconds that takes seconds in account.
354
- */
355
- function getTimezoneOffsetInMilliseconds(date) {
356
- var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
357
- utcDate.setUTCFullYear(date.getFullYear());
358
- return date.getTime() - utcDate.getTime();
359
- }
360
-
361
- function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); }
362
- /**
363
- * @name isDate
364
- * @category Common Helpers
365
- * @summary Is the given value a date?
366
- *
367
- * @description
368
- * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
369
- *
370
- * @param {*} value - the value to check
371
- * @returns {boolean} true if the given value is a date
372
- * @throws {TypeError} 1 arguments required
373
- *
374
- * @example
375
- * // For a valid date:
376
- * const result = isDate(new Date())
377
- * //=> true
378
- *
379
- * @example
380
- * // For an invalid date:
381
- * const result = isDate(new Date(NaN))
382
- * //=> true
383
- *
384
- * @example
385
- * // For some value:
386
- * const result = isDate('2014-02-31')
387
- * //=> false
388
- *
389
- * @example
390
- * // For an object:
391
- * const result = isDate({})
392
- * //=> false
393
- */
394
-
395
- function isDate(value) {
396
- requiredArgs(1, arguments);
397
- return value instanceof Date || _typeof$1(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
398
- }
399
-
400
- /**
401
- * @name isValid
402
- * @category Common Helpers
403
- * @summary Is the given date valid?
404
- *
405
- * @description
406
- * Returns false if argument is Invalid Date and true otherwise.
407
- * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
408
- * Invalid Date is a Date, whose time value is NaN.
409
- *
410
- * Time value of Date: http://es5.github.io/#x15.9.1.1
411
- *
412
- * @param {*} date - the date to check
413
- * @returns {Boolean} the date is valid
414
- * @throws {TypeError} 1 argument required
415
- *
416
- * @example
417
- * // For the valid date:
418
- * const result = isValid(new Date(2014, 1, 31))
419
- * //=> true
420
- *
421
- * @example
422
- * // For the value, convertable into a date:
423
- * const result = isValid(1393804800000)
424
- * //=> true
425
- *
426
- * @example
427
- * // For the invalid date:
428
- * const result = isValid(new Date(''))
429
- * //=> false
430
- */
431
-
432
- function isValid(dirtyDate) {
433
- requiredArgs(1, arguments);
434
-
435
- if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
436
- return false;
437
- }
438
-
439
- var date = toDate(dirtyDate);
440
- return !isNaN(Number(date));
441
- }
442
-
443
- /**
444
- * @name subMilliseconds
445
- * @category Millisecond Helpers
446
- * @summary Subtract the specified number of milliseconds from the given date.
447
- *
448
- * @description
449
- * Subtract the specified number of milliseconds from the given date.
450
- *
451
- * @param {Date|Number} date - the date to be changed
452
- * @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`.
453
- * @returns {Date} the new date with the milliseconds subtracted
454
- * @throws {TypeError} 2 arguments required
455
- *
456
- * @example
457
- * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
458
- * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
459
- * //=> Thu Jul 10 2014 12:45:29.250
460
- */
461
-
462
- function subMilliseconds(dirtyDate, dirtyAmount) {
463
- requiredArgs(2, arguments);
464
- var amount = toInteger(dirtyAmount);
465
- return addMilliseconds(dirtyDate, -amount);
466
- }
467
-
468
- var MILLISECONDS_IN_DAY = 86400000;
469
- function getUTCDayOfYear(dirtyDate) {
470
- requiredArgs(1, arguments);
471
- var date = toDate(dirtyDate);
472
- var timestamp = date.getTime();
473
- date.setUTCMonth(0, 1);
474
- date.setUTCHours(0, 0, 0, 0);
475
- var startOfYearTimestamp = date.getTime();
476
- var difference = timestamp - startOfYearTimestamp;
477
- return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
478
- }
479
-
480
- function startOfUTCISOWeek(dirtyDate) {
481
- requiredArgs(1, arguments);
482
- var weekStartsOn = 1;
483
- var date = toDate(dirtyDate);
484
- var day = date.getUTCDay();
485
- var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
486
- date.setUTCDate(date.getUTCDate() - diff);
487
- date.setUTCHours(0, 0, 0, 0);
488
- return date;
489
- }
490
-
491
- function getUTCISOWeekYear(dirtyDate) {
492
- requiredArgs(1, arguments);
493
- var date = toDate(dirtyDate);
494
- var year = date.getUTCFullYear();
495
- var fourthOfJanuaryOfNextYear = new Date(0);
496
- fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
497
- fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
498
- var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
499
- var fourthOfJanuaryOfThisYear = new Date(0);
500
- fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
501
- fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
502
- var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
503
-
504
- if (date.getTime() >= startOfNextYear.getTime()) {
505
- return year + 1;
506
- } else if (date.getTime() >= startOfThisYear.getTime()) {
507
- return year;
508
- } else {
509
- return year - 1;
510
- }
511
- }
512
-
513
- function startOfUTCISOWeekYear(dirtyDate) {
514
- requiredArgs(1, arguments);
515
- var year = getUTCISOWeekYear(dirtyDate);
516
- var fourthOfJanuary = new Date(0);
517
- fourthOfJanuary.setUTCFullYear(year, 0, 4);
518
- fourthOfJanuary.setUTCHours(0, 0, 0, 0);
519
- var date = startOfUTCISOWeek(fourthOfJanuary);
520
- return date;
521
- }
522
-
523
- var MILLISECONDS_IN_WEEK$1 = 604800000;
524
- function getUTCISOWeek(dirtyDate) {
525
- requiredArgs(1, arguments);
526
- var date = toDate(dirtyDate);
527
- var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer
528
- // because the number of milliseconds in a week is not constant
529
- // (e.g. it's different in the week of the daylight saving time clock shift)
530
-
531
- return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
532
- }
533
-
534
- function startOfUTCWeek(dirtyDate, options) {
535
- var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
536
-
537
- requiredArgs(1, arguments);
538
- var defaultOptions = getDefaultOptions();
539
- 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); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
540
-
541
- if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
542
- throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
543
- }
544
-
545
- var date = toDate(dirtyDate);
546
- var day = date.getUTCDay();
547
- var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
548
- date.setUTCDate(date.getUTCDate() - diff);
549
- date.setUTCHours(0, 0, 0, 0);
550
- return date;
551
- }
552
-
553
- function getUTCWeekYear(dirtyDate, options) {
554
- var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
555
-
556
- requiredArgs(1, arguments);
557
- var date = toDate(dirtyDate);
558
- var year = date.getUTCFullYear();
559
- var defaultOptions = getDefaultOptions();
560
- 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); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
561
-
562
- if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
563
- throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
564
- }
565
-
566
- var firstWeekOfNextYear = new Date(0);
567
- firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
568
- firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
569
- var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
570
- var firstWeekOfThisYear = new Date(0);
571
- firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
572
- firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
573
- var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
574
-
575
- if (date.getTime() >= startOfNextYear.getTime()) {
576
- return year + 1;
577
- } else if (date.getTime() >= startOfThisYear.getTime()) {
578
- return year;
579
- } else {
580
- return year - 1;
581
- }
582
- }
583
-
584
- function startOfUTCWeekYear(dirtyDate, options) {
585
- var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
586
-
587
- requiredArgs(1, arguments);
588
- var defaultOptions = getDefaultOptions();
589
- 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);
590
- var year = getUTCWeekYear(dirtyDate, options);
591
- var firstWeek = new Date(0);
592
- firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
593
- firstWeek.setUTCHours(0, 0, 0, 0);
594
- var date = startOfUTCWeek(firstWeek, options);
595
- return date;
596
- }
597
-
598
- var MILLISECONDS_IN_WEEK = 604800000;
599
- function getUTCWeek(dirtyDate, options) {
600
- requiredArgs(1, arguments);
601
- var date = toDate(dirtyDate);
602
- var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); // Round the number of days to the nearest integer
603
- // because the number of milliseconds in a week is not constant
604
- // (e.g. it's different in the week of the daylight saving time clock shift)
605
-
606
- return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
607
- }
608
-
609
- function addLeadingZeros(number, targetLength) {
610
- var sign = number < 0 ? '-' : '';
611
- var output = Math.abs(number).toString();
612
-
613
- while (output.length < targetLength) {
614
- output = '0' + output;
615
- }
616
-
617
- return sign + output;
618
- }
619
-
620
- /*
621
- * | | Unit | | Unit |
622
- * |-----|--------------------------------|-----|--------------------------------|
623
- * | a | AM, PM | A* | |
624
- * | d | Day of month | D | |
625
- * | h | Hour [1-12] | H | Hour [0-23] |
626
- * | m | Minute | M | Month |
627
- * | s | Second | S | Fraction of second |
628
- * | y | Year (abs) | Y | |
629
- *
630
- * Letters marked by * are not implemented but reserved by Unicode standard.
631
- */
632
-
633
- var formatters$1 = {
634
- // Year
635
- y: function y(date, token) {
636
- // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
637
- // | Year | y | yy | yyy | yyyy | yyyyy |
638
- // |----------|-------|----|-------|-------|-------|
639
- // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
640
- // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
641
- // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
642
- // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
643
- // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
644
- var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
645
-
646
- var year = signedYear > 0 ? signedYear : 1 - signedYear;
647
- return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
648
- },
649
- // Month
650
- M: function M(date, token) {
651
- var month = date.getUTCMonth();
652
- return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
653
- },
654
- // Day of the month
655
- d: function d(date, token) {
656
- return addLeadingZeros(date.getUTCDate(), token.length);
657
- },
658
- // AM or PM
659
- a: function a(date, token) {
660
- var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
661
-
662
- switch (token) {
663
- case 'a':
664
- case 'aa':
665
- return dayPeriodEnumValue.toUpperCase();
666
-
667
- case 'aaa':
668
- return dayPeriodEnumValue;
669
-
670
- case 'aaaaa':
671
- return dayPeriodEnumValue[0];
672
-
673
- case 'aaaa':
674
- default:
675
- return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
676
- }
677
- },
678
- // Hour [1-12]
679
- h: function h(date, token) {
680
- return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
681
- },
682
- // Hour [0-23]
683
- H: function H(date, token) {
684
- return addLeadingZeros(date.getUTCHours(), token.length);
685
- },
686
- // Minute
687
- m: function m(date, token) {
688
- return addLeadingZeros(date.getUTCMinutes(), token.length);
689
- },
690
- // Second
691
- s: function s(date, token) {
692
- return addLeadingZeros(date.getUTCSeconds(), token.length);
693
- },
694
- // Fraction of second
695
- S: function S(date, token) {
696
- var numberOfDigits = token.length;
697
- var milliseconds = date.getUTCMilliseconds();
698
- var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
699
- return addLeadingZeros(fractionalSeconds, token.length);
700
- }
701
- };
702
-
703
- var dayPeriodEnum = {
704
- am: 'am',
705
- pm: 'pm',
706
- midnight: 'midnight',
707
- noon: 'noon',
708
- morning: 'morning',
709
- afternoon: 'afternoon',
710
- evening: 'evening',
711
- night: 'night'
712
- };
713
-
714
- /*
715
- * | | Unit | | Unit |
716
- * |-----|--------------------------------|-----|--------------------------------|
717
- * | a | AM, PM | A* | Milliseconds in day |
718
- * | b | AM, PM, noon, midnight | B | Flexible day period |
719
- * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
720
- * | d | Day of month | D | Day of year |
721
- * | e | Local day of week | E | Day of week |
722
- * | f | | F* | Day of week in month |
723
- * | g* | Modified Julian day | G | Era |
724
- * | h | Hour [1-12] | H | Hour [0-23] |
725
- * | i! | ISO day of week | I! | ISO week of year |
726
- * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
727
- * | k | Hour [1-24] | K | Hour [0-11] |
728
- * | l* | (deprecated) | L | Stand-alone month |
729
- * | m | Minute | M | Month |
730
- * | n | | N | |
731
- * | o! | Ordinal number modifier | O | Timezone (GMT) |
732
- * | p! | Long localized time | P! | Long localized date |
733
- * | q | Stand-alone quarter | Q | Quarter |
734
- * | r* | Related Gregorian year | R! | ISO week-numbering year |
735
- * | s | Second | S | Fraction of second |
736
- * | t! | Seconds timestamp | T! | Milliseconds timestamp |
737
- * | u | Extended year | U* | Cyclic year |
738
- * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
739
- * | w | Local week of year | W* | Week of month |
740
- * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
741
- * | y | Year (abs) | Y | Local week-numbering year |
742
- * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
743
- *
744
- * Letters marked by * are not implemented but reserved by Unicode standard.
745
- *
746
- * Letters marked by ! are non-standard, but implemented by date-fns:
747
- * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
748
- * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
749
- * i.e. 7 for Sunday, 1 for Monday, etc.
750
- * - `I` is ISO week of year, as opposed to `w` which is local week of year.
751
- * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
752
- * `R` is supposed to be used in conjunction with `I` and `i`
753
- * for universal ISO week-numbering date, whereas
754
- * `Y` is supposed to be used in conjunction with `w` and `e`
755
- * for week-numbering date specific to the locale.
756
- * - `P` is long localized date format
757
- * - `p` is long localized time format
758
- */
759
- var formatters = {
760
- // Era
761
- G: function G(date, token, localize) {
762
- var era = date.getUTCFullYear() > 0 ? 1 : 0;
763
-
764
- switch (token) {
765
- // AD, BC
766
- case 'G':
767
- case 'GG':
768
- case 'GGG':
769
- return localize.era(era, {
770
- width: 'abbreviated'
771
- });
772
- // A, B
773
-
774
- case 'GGGGG':
775
- return localize.era(era, {
776
- width: 'narrow'
777
- });
778
- // Anno Domini, Before Christ
779
-
780
- case 'GGGG':
781
- default:
782
- return localize.era(era, {
783
- width: 'wide'
784
- });
785
- }
786
- },
787
- // Year
788
- y: function y(date, token, localize) {
789
- // Ordinal number
790
- if (token === 'yo') {
791
- var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
792
-
793
- var year = signedYear > 0 ? signedYear : 1 - signedYear;
794
- return localize.ordinalNumber(year, {
795
- unit: 'year'
796
- });
797
- }
798
-
799
- return formatters$1.y(date, token);
800
- },
801
- // Local week-numbering year
802
- Y: function Y(date, token, localize, options) {
803
- var signedWeekYear = getUTCWeekYear(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript)
804
-
805
- var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year
806
-
807
- if (token === 'YY') {
808
- var twoDigitYear = weekYear % 100;
809
- return addLeadingZeros(twoDigitYear, 2);
810
- } // Ordinal number
811
-
812
-
813
- if (token === 'Yo') {
814
- return localize.ordinalNumber(weekYear, {
815
- unit: 'year'
816
- });
817
- } // Padding
818
-
819
-
820
- return addLeadingZeros(weekYear, token.length);
821
- },
822
- // ISO week-numbering year
823
- R: function R(date, token) {
824
- var isoWeekYear = getUTCISOWeekYear(date); // Padding
825
-
826
- return addLeadingZeros(isoWeekYear, token.length);
827
- },
828
- // Extended year. This is a single number designating the year of this calendar system.
829
- // The main difference between `y` and `u` localizers are B.C. years:
830
- // | Year | `y` | `u` |
831
- // |------|-----|-----|
832
- // | AC 1 | 1 | 1 |
833
- // | BC 1 | 1 | 0 |
834
- // | BC 2 | 2 | -1 |
835
- // Also `yy` always returns the last two digits of a year,
836
- // while `uu` pads single digit years to 2 characters and returns other years unchanged.
837
- u: function u(date, token) {
838
- var year = date.getUTCFullYear();
839
- return addLeadingZeros(year, token.length);
840
- },
841
- // Quarter
842
- Q: function Q(date, token, localize) {
843
- var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
844
-
845
- switch (token) {
846
- // 1, 2, 3, 4
847
- case 'Q':
848
- return String(quarter);
849
- // 01, 02, 03, 04
850
-
851
- case 'QQ':
852
- return addLeadingZeros(quarter, 2);
853
- // 1st, 2nd, 3rd, 4th
854
-
855
- case 'Qo':
856
- return localize.ordinalNumber(quarter, {
857
- unit: 'quarter'
858
- });
859
- // Q1, Q2, Q3, Q4
860
-
861
- case 'QQQ':
862
- return localize.quarter(quarter, {
863
- width: 'abbreviated',
864
- context: 'formatting'
865
- });
866
- // 1, 2, 3, 4 (narrow quarter; could be not numerical)
867
-
868
- case 'QQQQQ':
869
- return localize.quarter(quarter, {
870
- width: 'narrow',
871
- context: 'formatting'
872
- });
873
- // 1st quarter, 2nd quarter, ...
874
-
875
- case 'QQQQ':
876
- default:
877
- return localize.quarter(quarter, {
878
- width: 'wide',
879
- context: 'formatting'
880
- });
881
- }
882
- },
883
- // Stand-alone quarter
884
- q: function q(date, token, localize) {
885
- var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
886
-
887
- switch (token) {
888
- // 1, 2, 3, 4
889
- case 'q':
890
- return String(quarter);
891
- // 01, 02, 03, 04
892
-
893
- case 'qq':
894
- return addLeadingZeros(quarter, 2);
895
- // 1st, 2nd, 3rd, 4th
896
-
897
- case 'qo':
898
- return localize.ordinalNumber(quarter, {
899
- unit: 'quarter'
900
- });
901
- // Q1, Q2, Q3, Q4
902
-
903
- case 'qqq':
904
- return localize.quarter(quarter, {
905
- width: 'abbreviated',
906
- context: 'standalone'
907
- });
908
- // 1, 2, 3, 4 (narrow quarter; could be not numerical)
909
-
910
- case 'qqqqq':
911
- return localize.quarter(quarter, {
912
- width: 'narrow',
913
- context: 'standalone'
914
- });
915
- // 1st quarter, 2nd quarter, ...
916
-
917
- case 'qqqq':
918
- default:
919
- return localize.quarter(quarter, {
920
- width: 'wide',
921
- context: 'standalone'
922
- });
923
- }
924
- },
925
- // Month
926
- M: function M(date, token, localize) {
927
- var month = date.getUTCMonth();
928
-
929
- switch (token) {
930
- case 'M':
931
- case 'MM':
932
- return formatters$1.M(date, token);
933
- // 1st, 2nd, ..., 12th
934
-
935
- case 'Mo':
936
- return localize.ordinalNumber(month + 1, {
937
- unit: 'month'
938
- });
939
- // Jan, Feb, ..., Dec
940
-
941
- case 'MMM':
942
- return localize.month(month, {
943
- width: 'abbreviated',
944
- context: 'formatting'
945
- });
946
- // J, F, ..., D
947
-
948
- case 'MMMMM':
949
- return localize.month(month, {
950
- width: 'narrow',
951
- context: 'formatting'
952
- });
953
- // January, February, ..., December
954
-
955
- case 'MMMM':
956
- default:
957
- return localize.month(month, {
958
- width: 'wide',
959
- context: 'formatting'
960
- });
961
- }
962
- },
963
- // Stand-alone month
964
- L: function L(date, token, localize) {
965
- var month = date.getUTCMonth();
966
-
967
- switch (token) {
968
- // 1, 2, ..., 12
969
- case 'L':
970
- return String(month + 1);
971
- // 01, 02, ..., 12
972
-
973
- case 'LL':
974
- return addLeadingZeros(month + 1, 2);
975
- // 1st, 2nd, ..., 12th
976
-
977
- case 'Lo':
978
- return localize.ordinalNumber(month + 1, {
979
- unit: 'month'
980
- });
981
- // Jan, Feb, ..., Dec
982
-
983
- case 'LLL':
984
- return localize.month(month, {
985
- width: 'abbreviated',
986
- context: 'standalone'
987
- });
988
- // J, F, ..., D
989
-
990
- case 'LLLLL':
991
- return localize.month(month, {
992
- width: 'narrow',
993
- context: 'standalone'
994
- });
995
- // January, February, ..., December
996
-
997
- case 'LLLL':
998
- default:
999
- return localize.month(month, {
1000
- width: 'wide',
1001
- context: 'standalone'
1002
- });
1003
- }
1004
- },
1005
- // Local week of year
1006
- w: function w(date, token, localize, options) {
1007
- var week = getUTCWeek(date, options);
1008
-
1009
- if (token === 'wo') {
1010
- return localize.ordinalNumber(week, {
1011
- unit: 'week'
1012
- });
1013
- }
1014
-
1015
- return addLeadingZeros(week, token.length);
1016
- },
1017
- // ISO week of year
1018
- I: function I(date, token, localize) {
1019
- var isoWeek = getUTCISOWeek(date);
1020
-
1021
- if (token === 'Io') {
1022
- return localize.ordinalNumber(isoWeek, {
1023
- unit: 'week'
1024
- });
1025
- }
1026
-
1027
- return addLeadingZeros(isoWeek, token.length);
1028
- },
1029
- // Day of the month
1030
- d: function d(date, token, localize) {
1031
- if (token === 'do') {
1032
- return localize.ordinalNumber(date.getUTCDate(), {
1033
- unit: 'date'
1034
- });
1035
- }
1036
-
1037
- return formatters$1.d(date, token);
1038
- },
1039
- // Day of year
1040
- D: function D(date, token, localize) {
1041
- var dayOfYear = getUTCDayOfYear(date);
1042
-
1043
- if (token === 'Do') {
1044
- return localize.ordinalNumber(dayOfYear, {
1045
- unit: 'dayOfYear'
1046
- });
1047
- }
1048
-
1049
- return addLeadingZeros(dayOfYear, token.length);
1050
- },
1051
- // Day of week
1052
- E: function E(date, token, localize) {
1053
- var dayOfWeek = date.getUTCDay();
1054
-
1055
- switch (token) {
1056
- // Tue
1057
- case 'E':
1058
- case 'EE':
1059
- case 'EEE':
1060
- return localize.day(dayOfWeek, {
1061
- width: 'abbreviated',
1062
- context: 'formatting'
1063
- });
1064
- // T
1065
-
1066
- case 'EEEEE':
1067
- return localize.day(dayOfWeek, {
1068
- width: 'narrow',
1069
- context: 'formatting'
1070
- });
1071
- // Tu
1072
-
1073
- case 'EEEEEE':
1074
- return localize.day(dayOfWeek, {
1075
- width: 'short',
1076
- context: 'formatting'
1077
- });
1078
- // Tuesday
1079
-
1080
- case 'EEEE':
1081
- default:
1082
- return localize.day(dayOfWeek, {
1083
- width: 'wide',
1084
- context: 'formatting'
1085
- });
1086
- }
1087
- },
1088
- // Local day of week
1089
- e: function e(date, token, localize, options) {
1090
- var dayOfWeek = date.getUTCDay();
1091
- var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
1092
-
1093
- switch (token) {
1094
- // Numerical value (Nth day of week with current locale or weekStartsOn)
1095
- case 'e':
1096
- return String(localDayOfWeek);
1097
- // Padded numerical value
1098
-
1099
- case 'ee':
1100
- return addLeadingZeros(localDayOfWeek, 2);
1101
- // 1st, 2nd, ..., 7th
1102
-
1103
- case 'eo':
1104
- return localize.ordinalNumber(localDayOfWeek, {
1105
- unit: 'day'
1106
- });
1107
-
1108
- case 'eee':
1109
- return localize.day(dayOfWeek, {
1110
- width: 'abbreviated',
1111
- context: 'formatting'
1112
- });
1113
- // T
1114
-
1115
- case 'eeeee':
1116
- return localize.day(dayOfWeek, {
1117
- width: 'narrow',
1118
- context: 'formatting'
1119
- });
1120
- // Tu
1121
-
1122
- case 'eeeeee':
1123
- return localize.day(dayOfWeek, {
1124
- width: 'short',
1125
- context: 'formatting'
1126
- });
1127
- // Tuesday
1128
-
1129
- case 'eeee':
1130
- default:
1131
- return localize.day(dayOfWeek, {
1132
- width: 'wide',
1133
- context: 'formatting'
1134
- });
1135
- }
1136
- },
1137
- // Stand-alone local day of week
1138
- c: function c(date, token, localize, options) {
1139
- var dayOfWeek = date.getUTCDay();
1140
- var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
1141
-
1142
- switch (token) {
1143
- // Numerical value (same as in `e`)
1144
- case 'c':
1145
- return String(localDayOfWeek);
1146
- // Padded numerical value
1147
-
1148
- case 'cc':
1149
- return addLeadingZeros(localDayOfWeek, token.length);
1150
- // 1st, 2nd, ..., 7th
1151
-
1152
- case 'co':
1153
- return localize.ordinalNumber(localDayOfWeek, {
1154
- unit: 'day'
1155
- });
1156
-
1157
- case 'ccc':
1158
- return localize.day(dayOfWeek, {
1159
- width: 'abbreviated',
1160
- context: 'standalone'
1161
- });
1162
- // T
1163
-
1164
- case 'ccccc':
1165
- return localize.day(dayOfWeek, {
1166
- width: 'narrow',
1167
- context: 'standalone'
1168
- });
1169
- // Tu
1170
-
1171
- case 'cccccc':
1172
- return localize.day(dayOfWeek, {
1173
- width: 'short',
1174
- context: 'standalone'
1175
- });
1176
- // Tuesday
1177
-
1178
- case 'cccc':
1179
- default:
1180
- return localize.day(dayOfWeek, {
1181
- width: 'wide',
1182
- context: 'standalone'
1183
- });
1184
- }
1185
- },
1186
- // ISO day of week
1187
- i: function i(date, token, localize) {
1188
- var dayOfWeek = date.getUTCDay();
1189
- var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
1190
-
1191
- switch (token) {
1192
- // 2
1193
- case 'i':
1194
- return String(isoDayOfWeek);
1195
- // 02
1196
-
1197
- case 'ii':
1198
- return addLeadingZeros(isoDayOfWeek, token.length);
1199
- // 2nd
1200
-
1201
- case 'io':
1202
- return localize.ordinalNumber(isoDayOfWeek, {
1203
- unit: 'day'
1204
- });
1205
- // Tue
1206
-
1207
- case 'iii':
1208
- return localize.day(dayOfWeek, {
1209
- width: 'abbreviated',
1210
- context: 'formatting'
1211
- });
1212
- // T
1213
-
1214
- case 'iiiii':
1215
- return localize.day(dayOfWeek, {
1216
- width: 'narrow',
1217
- context: 'formatting'
1218
- });
1219
- // Tu
1220
-
1221
- case 'iiiiii':
1222
- return localize.day(dayOfWeek, {
1223
- width: 'short',
1224
- context: 'formatting'
1225
- });
1226
- // Tuesday
1227
-
1228
- case 'iiii':
1229
- default:
1230
- return localize.day(dayOfWeek, {
1231
- width: 'wide',
1232
- context: 'formatting'
1233
- });
1234
- }
1235
- },
1236
- // AM or PM
1237
- a: function a(date, token, localize) {
1238
- var hours = date.getUTCHours();
1239
- var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
1240
-
1241
- switch (token) {
1242
- case 'a':
1243
- case 'aa':
1244
- return localize.dayPeriod(dayPeriodEnumValue, {
1245
- width: 'abbreviated',
1246
- context: 'formatting'
1247
- });
1248
-
1249
- case 'aaa':
1250
- return localize.dayPeriod(dayPeriodEnumValue, {
1251
- width: 'abbreviated',
1252
- context: 'formatting'
1253
- }).toLowerCase();
1254
-
1255
- case 'aaaaa':
1256
- return localize.dayPeriod(dayPeriodEnumValue, {
1257
- width: 'narrow',
1258
- context: 'formatting'
1259
- });
1260
-
1261
- case 'aaaa':
1262
- default:
1263
- return localize.dayPeriod(dayPeriodEnumValue, {
1264
- width: 'wide',
1265
- context: 'formatting'
1266
- });
1267
- }
1268
- },
1269
- // AM, PM, midnight, noon
1270
- b: function b(date, token, localize) {
1271
- var hours = date.getUTCHours();
1272
- var dayPeriodEnumValue;
1273
-
1274
- if (hours === 12) {
1275
- dayPeriodEnumValue = dayPeriodEnum.noon;
1276
- } else if (hours === 0) {
1277
- dayPeriodEnumValue = dayPeriodEnum.midnight;
1278
- } else {
1279
- dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
1280
- }
1281
-
1282
- switch (token) {
1283
- case 'b':
1284
- case 'bb':
1285
- return localize.dayPeriod(dayPeriodEnumValue, {
1286
- width: 'abbreviated',
1287
- context: 'formatting'
1288
- });
1289
-
1290
- case 'bbb':
1291
- return localize.dayPeriod(dayPeriodEnumValue, {
1292
- width: 'abbreviated',
1293
- context: 'formatting'
1294
- }).toLowerCase();
1295
-
1296
- case 'bbbbb':
1297
- return localize.dayPeriod(dayPeriodEnumValue, {
1298
- width: 'narrow',
1299
- context: 'formatting'
1300
- });
1301
-
1302
- case 'bbbb':
1303
- default:
1304
- return localize.dayPeriod(dayPeriodEnumValue, {
1305
- width: 'wide',
1306
- context: 'formatting'
1307
- });
1308
- }
1309
- },
1310
- // in the morning, in the afternoon, in the evening, at night
1311
- B: function B(date, token, localize) {
1312
- var hours = date.getUTCHours();
1313
- var dayPeriodEnumValue;
1314
-
1315
- if (hours >= 17) {
1316
- dayPeriodEnumValue = dayPeriodEnum.evening;
1317
- } else if (hours >= 12) {
1318
- dayPeriodEnumValue = dayPeriodEnum.afternoon;
1319
- } else if (hours >= 4) {
1320
- dayPeriodEnumValue = dayPeriodEnum.morning;
1321
- } else {
1322
- dayPeriodEnumValue = dayPeriodEnum.night;
1323
- }
1324
-
1325
- switch (token) {
1326
- case 'B':
1327
- case 'BB':
1328
- case 'BBB':
1329
- return localize.dayPeriod(dayPeriodEnumValue, {
1330
- width: 'abbreviated',
1331
- context: 'formatting'
1332
- });
1333
-
1334
- case 'BBBBB':
1335
- return localize.dayPeriod(dayPeriodEnumValue, {
1336
- width: 'narrow',
1337
- context: 'formatting'
1338
- });
1339
-
1340
- case 'BBBB':
1341
- default:
1342
- return localize.dayPeriod(dayPeriodEnumValue, {
1343
- width: 'wide',
1344
- context: 'formatting'
1345
- });
1346
- }
1347
- },
1348
- // Hour [1-12]
1349
- h: function h(date, token, localize) {
1350
- if (token === 'ho') {
1351
- var hours = date.getUTCHours() % 12;
1352
- if (hours === 0) hours = 12;
1353
- return localize.ordinalNumber(hours, {
1354
- unit: 'hour'
1355
- });
1356
- }
1357
-
1358
- return formatters$1.h(date, token);
1359
- },
1360
- // Hour [0-23]
1361
- H: function H(date, token, localize) {
1362
- if (token === 'Ho') {
1363
- return localize.ordinalNumber(date.getUTCHours(), {
1364
- unit: 'hour'
1365
- });
1366
- }
1367
-
1368
- return formatters$1.H(date, token);
1369
- },
1370
- // Hour [0-11]
1371
- K: function K(date, token, localize) {
1372
- var hours = date.getUTCHours() % 12;
1373
-
1374
- if (token === 'Ko') {
1375
- return localize.ordinalNumber(hours, {
1376
- unit: 'hour'
1377
- });
1378
- }
1379
-
1380
- return addLeadingZeros(hours, token.length);
1381
- },
1382
- // Hour [1-24]
1383
- k: function k(date, token, localize) {
1384
- var hours = date.getUTCHours();
1385
- if (hours === 0) hours = 24;
1386
-
1387
- if (token === 'ko') {
1388
- return localize.ordinalNumber(hours, {
1389
- unit: 'hour'
1390
- });
1391
- }
1392
-
1393
- return addLeadingZeros(hours, token.length);
1394
- },
1395
- // Minute
1396
- m: function m(date, token, localize) {
1397
- if (token === 'mo') {
1398
- return localize.ordinalNumber(date.getUTCMinutes(), {
1399
- unit: 'minute'
1400
- });
1401
- }
1402
-
1403
- return formatters$1.m(date, token);
1404
- },
1405
- // Second
1406
- s: function s(date, token, localize) {
1407
- if (token === 'so') {
1408
- return localize.ordinalNumber(date.getUTCSeconds(), {
1409
- unit: 'second'
1410
- });
1411
- }
1412
-
1413
- return formatters$1.s(date, token);
1414
- },
1415
- // Fraction of second
1416
- S: function S(date, token) {
1417
- return formatters$1.S(date, token);
1418
- },
1419
- // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
1420
- X: function X(date, token, _localize, options) {
1421
- var originalDate = options._originalDate || date;
1422
- var timezoneOffset = originalDate.getTimezoneOffset();
1423
-
1424
- if (timezoneOffset === 0) {
1425
- return 'Z';
1426
- }
1427
-
1428
- switch (token) {
1429
- // Hours and optional minutes
1430
- case 'X':
1431
- return formatTimezoneWithOptionalMinutes(timezoneOffset);
1432
- // Hours, minutes and optional seconds without `:` delimiter
1433
- // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1434
- // so this token always has the same output as `XX`
1435
-
1436
- case 'XXXX':
1437
- case 'XX':
1438
- // Hours and minutes without `:` delimiter
1439
- return formatTimezone(timezoneOffset);
1440
- // Hours, minutes and optional seconds with `:` delimiter
1441
- // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1442
- // so this token always has the same output as `XXX`
1443
-
1444
- case 'XXXXX':
1445
- case 'XXX': // Hours and minutes with `:` delimiter
1446
-
1447
- default:
1448
- return formatTimezone(timezoneOffset, ':');
1449
- }
1450
- },
1451
- // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
1452
- x: function x(date, token, _localize, options) {
1453
- var originalDate = options._originalDate || date;
1454
- var timezoneOffset = originalDate.getTimezoneOffset();
1455
-
1456
- switch (token) {
1457
- // Hours and optional minutes
1458
- case 'x':
1459
- return formatTimezoneWithOptionalMinutes(timezoneOffset);
1460
- // Hours, minutes and optional seconds without `:` delimiter
1461
- // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1462
- // so this token always has the same output as `xx`
1463
-
1464
- case 'xxxx':
1465
- case 'xx':
1466
- // Hours and minutes without `:` delimiter
1467
- return formatTimezone(timezoneOffset);
1468
- // Hours, minutes and optional seconds with `:` delimiter
1469
- // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1470
- // so this token always has the same output as `xxx`
1471
-
1472
- case 'xxxxx':
1473
- case 'xxx': // Hours and minutes with `:` delimiter
1474
-
1475
- default:
1476
- return formatTimezone(timezoneOffset, ':');
1477
- }
1478
- },
1479
- // Timezone (GMT)
1480
- O: function O(date, token, _localize, options) {
1481
- var originalDate = options._originalDate || date;
1482
- var timezoneOffset = originalDate.getTimezoneOffset();
1483
-
1484
- switch (token) {
1485
- // Short
1486
- case 'O':
1487
- case 'OO':
1488
- case 'OOO':
1489
- return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1490
- // Long
1491
-
1492
- case 'OOOO':
1493
- default:
1494
- return 'GMT' + formatTimezone(timezoneOffset, ':');
1495
- }
1496
- },
1497
- // Timezone (specific non-location)
1498
- z: function z(date, token, _localize, options) {
1499
- var originalDate = options._originalDate || date;
1500
- var timezoneOffset = originalDate.getTimezoneOffset();
1501
-
1502
- switch (token) {
1503
- // Short
1504
- case 'z':
1505
- case 'zz':
1506
- case 'zzz':
1507
- return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1508
- // Long
1509
-
1510
- case 'zzzz':
1511
- default:
1512
- return 'GMT' + formatTimezone(timezoneOffset, ':');
1513
- }
1514
- },
1515
- // Seconds timestamp
1516
- t: function t(date, token, _localize, options) {
1517
- var originalDate = options._originalDate || date;
1518
- var timestamp = Math.floor(originalDate.getTime() / 1000);
1519
- return addLeadingZeros(timestamp, token.length);
1520
- },
1521
- // Milliseconds timestamp
1522
- T: function T(date, token, _localize, options) {
1523
- var originalDate = options._originalDate || date;
1524
- var timestamp = originalDate.getTime();
1525
- return addLeadingZeros(timestamp, token.length);
1526
- }
1527
- };
1528
-
1529
- function formatTimezoneShort(offset, dirtyDelimiter) {
1530
- var sign = offset > 0 ? '-' : '+';
1531
- var absOffset = Math.abs(offset);
1532
- var hours = Math.floor(absOffset / 60);
1533
- var minutes = absOffset % 60;
1534
-
1535
- if (minutes === 0) {
1536
- return sign + String(hours);
1537
- }
1538
-
1539
- var delimiter = dirtyDelimiter || '';
1540
- return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
1541
- }
1542
-
1543
- function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
1544
- if (offset % 60 === 0) {
1545
- var sign = offset > 0 ? '-' : '+';
1546
- return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
1547
- }
1548
-
1549
- return formatTimezone(offset, dirtyDelimiter);
1550
- }
1551
-
1552
- function formatTimezone(offset, dirtyDelimiter) {
1553
- var delimiter = dirtyDelimiter || '';
1554
- var sign = offset > 0 ? '-' : '+';
1555
- var absOffset = Math.abs(offset);
1556
- var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
1557
- var minutes = addLeadingZeros(absOffset % 60, 2);
1558
- return sign + hours + delimiter + minutes;
1559
- }
1560
-
1561
- var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
1562
- switch (pattern) {
1563
- case 'P':
1564
- return formatLong.date({
1565
- width: 'short'
1566
- });
1567
-
1568
- case 'PP':
1569
- return formatLong.date({
1570
- width: 'medium'
1571
- });
1572
-
1573
- case 'PPP':
1574
- return formatLong.date({
1575
- width: 'long'
1576
- });
1577
-
1578
- case 'PPPP':
1579
- default:
1580
- return formatLong.date({
1581
- width: 'full'
1582
- });
1583
- }
1584
- };
1585
-
1586
- var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
1587
- switch (pattern) {
1588
- case 'p':
1589
- return formatLong.time({
1590
- width: 'short'
1591
- });
1592
-
1593
- case 'pp':
1594
- return formatLong.time({
1595
- width: 'medium'
1596
- });
1597
-
1598
- case 'ppp':
1599
- return formatLong.time({
1600
- width: 'long'
1601
- });
1602
-
1603
- case 'pppp':
1604
- default:
1605
- return formatLong.time({
1606
- width: 'full'
1607
- });
1608
- }
1609
- };
1610
-
1611
- var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
1612
- var matchResult = pattern.match(/(P+)(p+)?/) || [];
1613
- var datePattern = matchResult[1];
1614
- var timePattern = matchResult[2];
1615
-
1616
- if (!timePattern) {
1617
- return dateLongFormatter(pattern, formatLong);
1618
- }
1619
-
1620
- var dateTimeFormat;
1621
-
1622
- switch (datePattern) {
1623
- case 'P':
1624
- dateTimeFormat = formatLong.dateTime({
1625
- width: 'short'
1626
- });
1627
- break;
1628
-
1629
- case 'PP':
1630
- dateTimeFormat = formatLong.dateTime({
1631
- width: 'medium'
1632
- });
1633
- break;
1634
-
1635
- case 'PPP':
1636
- dateTimeFormat = formatLong.dateTime({
1637
- width: 'long'
1638
- });
1639
- break;
1640
-
1641
- case 'PPPP':
1642
- default:
1643
- dateTimeFormat = formatLong.dateTime({
1644
- width: 'full'
1645
- });
1646
- break;
1647
- }
1648
-
1649
- return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
1650
- };
1651
-
1652
- var longFormatters = {
1653
- p: timeLongFormatter,
1654
- P: dateTimeLongFormatter
1655
- };
1656
-
1657
- var protectedDayOfYearTokens = ['D', 'DD'];
1658
- var protectedWeekYearTokens = ['YY', 'YYYY'];
1659
- function isProtectedDayOfYearToken(token) {
1660
- return protectedDayOfYearTokens.indexOf(token) !== -1;
1661
- }
1662
- function isProtectedWeekYearToken(token) {
1663
- return protectedWeekYearTokens.indexOf(token) !== -1;
1664
- }
1665
- function throwProtectedError(token, format, input) {
1666
- if (token === 'YYYY') {
1667
- 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"));
1668
- } else if (token === 'YY') {
1669
- 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"));
1670
- } else if (token === 'D') {
1671
- 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"));
1672
- } else if (token === 'DD') {
1673
- 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"));
1674
- }
1675
- }
1676
-
1677
- var formatDistanceLocale = {
1678
- lessThanXSeconds: {
1679
- one: 'less than a second',
1680
- other: 'less than {{count}} seconds'
1681
- },
1682
- xSeconds: {
1683
- one: '1 second',
1684
- other: '{{count}} seconds'
1685
- },
1686
- halfAMinute: 'half a minute',
1687
- lessThanXMinutes: {
1688
- one: 'less than a minute',
1689
- other: 'less than {{count}} minutes'
1690
- },
1691
- xMinutes: {
1692
- one: '1 minute',
1693
- other: '{{count}} minutes'
1694
- },
1695
- aboutXHours: {
1696
- one: 'about 1 hour',
1697
- other: 'about {{count}} hours'
1698
- },
1699
- xHours: {
1700
- one: '1 hour',
1701
- other: '{{count}} hours'
1702
- },
1703
- xDays: {
1704
- one: '1 day',
1705
- other: '{{count}} days'
1706
- },
1707
- aboutXWeeks: {
1708
- one: 'about 1 week',
1709
- other: 'about {{count}} weeks'
1710
- },
1711
- xWeeks: {
1712
- one: '1 week',
1713
- other: '{{count}} weeks'
1714
- },
1715
- aboutXMonths: {
1716
- one: 'about 1 month',
1717
- other: 'about {{count}} months'
1718
- },
1719
- xMonths: {
1720
- one: '1 month',
1721
- other: '{{count}} months'
1722
- },
1723
- aboutXYears: {
1724
- one: 'about 1 year',
1725
- other: 'about {{count}} years'
1726
- },
1727
- xYears: {
1728
- one: '1 year',
1729
- other: '{{count}} years'
1730
- },
1731
- overXYears: {
1732
- one: 'over 1 year',
1733
- other: 'over {{count}} years'
1734
- },
1735
- almostXYears: {
1736
- one: 'almost 1 year',
1737
- other: 'almost {{count}} years'
1738
- }
1739
- };
1740
-
1741
- var formatDistance = function formatDistance(token, count, options) {
1742
- var result;
1743
- var tokenValue = formatDistanceLocale[token];
1744
-
1745
- if (typeof tokenValue === 'string') {
1746
- result = tokenValue;
1747
- } else if (count === 1) {
1748
- result = tokenValue.one;
1749
- } else {
1750
- result = tokenValue.other.replace('{{count}}', count.toString());
1751
- }
1752
-
1753
- if (options !== null && options !== void 0 && options.addSuffix) {
1754
- if (options.comparison && options.comparison > 0) {
1755
- return 'in ' + result;
1756
- } else {
1757
- return result + ' ago';
1758
- }
1759
- }
1760
-
1761
- return result;
1762
- };
1763
-
1764
- function buildFormatLongFn(args) {
1765
- return function () {
1766
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1767
- // TODO: Remove String()
1768
- var width = options.width ? String(options.width) : args.defaultWidth;
1769
- var format = args.formats[width] || args.formats[args.defaultWidth];
1770
- return format;
1771
- };
1772
- }
1773
-
1774
- var dateFormats = {
1775
- full: 'EEEE, MMMM do, y',
1776
- long: 'MMMM do, y',
1777
- medium: 'MMM d, y',
1778
- short: 'MM/dd/yyyy'
1779
- };
1780
- var timeFormats = {
1781
- full: 'h:mm:ss a zzzz',
1782
- long: 'h:mm:ss a z',
1783
- medium: 'h:mm:ss a',
1784
- short: 'h:mm a'
1785
- };
1786
- var dateTimeFormats = {
1787
- full: "{{date}} 'at' {{time}}",
1788
- long: "{{date}} 'at' {{time}}",
1789
- medium: '{{date}}, {{time}}',
1790
- short: '{{date}}, {{time}}'
1791
- };
1792
- var formatLong = {
1793
- date: buildFormatLongFn({
1794
- formats: dateFormats,
1795
- defaultWidth: 'full'
1796
- }),
1797
- time: buildFormatLongFn({
1798
- formats: timeFormats,
1799
- defaultWidth: 'full'
1800
- }),
1801
- dateTime: buildFormatLongFn({
1802
- formats: dateTimeFormats,
1803
- defaultWidth: 'full'
1804
- })
1805
- };
1806
-
1807
- var formatRelativeLocale = {
1808
- lastWeek: "'last' eeee 'at' p",
1809
- yesterday: "'yesterday at' p",
1810
- today: "'today at' p",
1811
- tomorrow: "'tomorrow at' p",
1812
- nextWeek: "eeee 'at' p",
1813
- other: 'P'
1814
- };
1815
-
1816
- var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
1817
- return formatRelativeLocale[token];
1818
- };
1819
-
1820
- function buildLocalizeFn(args) {
1821
- return function (dirtyIndex, options) {
1822
- var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
1823
- var valuesArray;
1824
-
1825
- if (context === 'formatting' && args.formattingValues) {
1826
- var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
1827
- var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
1828
- valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
1829
- } else {
1830
- var _defaultWidth = args.defaultWidth;
1831
-
1832
- var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
1833
-
1834
- valuesArray = args.values[_width] || args.values[_defaultWidth];
1835
- }
1836
-
1837
- var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; // @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!
1838
-
1839
- return valuesArray[index];
1840
- };
1841
- }
1842
-
1843
- var eraValues = {
1844
- narrow: ['B', 'A'],
1845
- abbreviated: ['BC', 'AD'],
1846
- wide: ['Before Christ', 'Anno Domini']
1847
- };
1848
- var quarterValues = {
1849
- narrow: ['1', '2', '3', '4'],
1850
- abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
1851
- wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
1852
- }; // Note: in English, the names of days of the week and months are capitalized.
1853
- // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1854
- // Generally, formatted dates should look like they are in the middle of a sentence,
1855
- // e.g. in Spanish language the weekdays and months should be in the lowercase.
1856
-
1857
- var monthValues = {
1858
- narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
1859
- abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
1860
- wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
1861
- };
1862
- var dayValues = {
1863
- narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
1864
- short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
1865
- abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
1866
- wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
1867
- };
1868
- var dayPeriodValues = {
1869
- narrow: {
1870
- am: 'a',
1871
- pm: 'p',
1872
- midnight: 'mi',
1873
- noon: 'n',
1874
- morning: 'morning',
1875
- afternoon: 'afternoon',
1876
- evening: 'evening',
1877
- night: 'night'
1878
- },
1879
- abbreviated: {
1880
- am: 'AM',
1881
- pm: 'PM',
1882
- midnight: 'midnight',
1883
- noon: 'noon',
1884
- morning: 'morning',
1885
- afternoon: 'afternoon',
1886
- evening: 'evening',
1887
- night: 'night'
1888
- },
1889
- wide: {
1890
- am: 'a.m.',
1891
- pm: 'p.m.',
1892
- midnight: 'midnight',
1893
- noon: 'noon',
1894
- morning: 'morning',
1895
- afternoon: 'afternoon',
1896
- evening: 'evening',
1897
- night: 'night'
1898
- }
1899
- };
1900
- var formattingDayPeriodValues = {
1901
- narrow: {
1902
- am: 'a',
1903
- pm: 'p',
1904
- midnight: 'mi',
1905
- noon: 'n',
1906
- morning: 'in the morning',
1907
- afternoon: 'in the afternoon',
1908
- evening: 'in the evening',
1909
- night: 'at night'
1910
- },
1911
- abbreviated: {
1912
- am: 'AM',
1913
- pm: 'PM',
1914
- midnight: 'midnight',
1915
- noon: 'noon',
1916
- morning: 'in the morning',
1917
- afternoon: 'in the afternoon',
1918
- evening: 'in the evening',
1919
- night: 'at night'
1920
- },
1921
- wide: {
1922
- am: 'a.m.',
1923
- pm: 'p.m.',
1924
- midnight: 'midnight',
1925
- noon: 'noon',
1926
- morning: 'in the morning',
1927
- afternoon: 'in the afternoon',
1928
- evening: 'in the evening',
1929
- night: 'at night'
1930
- }
1931
- };
1932
-
1933
- var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
1934
- var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example,
1935
- // if they are different for different grammatical genders,
1936
- // use `options.unit`.
1937
- //
1938
- // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
1939
- // 'day', 'hour', 'minute', 'second'.
1940
-
1941
- var rem100 = number % 100;
1942
-
1943
- if (rem100 > 20 || rem100 < 10) {
1944
- switch (rem100 % 10) {
1945
- case 1:
1946
- return number + 'st';
1947
-
1948
- case 2:
1949
- return number + 'nd';
1950
-
1951
- case 3:
1952
- return number + 'rd';
1953
- }
1954
- }
1955
-
1956
- return number + 'th';
1957
- };
1958
-
1959
- var localize = {
1960
- ordinalNumber: ordinalNumber,
1961
- era: buildLocalizeFn({
1962
- values: eraValues,
1963
- defaultWidth: 'wide'
1964
- }),
1965
- quarter: buildLocalizeFn({
1966
- values: quarterValues,
1967
- defaultWidth: 'wide',
1968
- argumentCallback: function argumentCallback(quarter) {
1969
- return quarter - 1;
1970
- }
1971
- }),
1972
- month: buildLocalizeFn({
1973
- values: monthValues,
1974
- defaultWidth: 'wide'
1975
- }),
1976
- day: buildLocalizeFn({
1977
- values: dayValues,
1978
- defaultWidth: 'wide'
1979
- }),
1980
- dayPeriod: buildLocalizeFn({
1981
- values: dayPeriodValues,
1982
- defaultWidth: 'wide',
1983
- formattingValues: formattingDayPeriodValues,
1984
- defaultFormattingWidth: 'wide'
1985
- })
1986
- };
1987
-
1988
- function buildMatchFn(args) {
1989
- return function (string) {
1990
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1991
- var width = options.width;
1992
- var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
1993
- var matchResult = string.match(matchPattern);
1994
-
1995
- if (!matchResult) {
1996
- return null;
1997
- }
1998
-
1999
- var matchedString = matchResult[0];
2000
- var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
2001
- var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
2002
- return pattern.test(matchedString);
2003
- }) : findKey(parsePatterns, function (pattern) {
2004
- return pattern.test(matchedString);
2005
- });
2006
- var value;
2007
- value = args.valueCallback ? args.valueCallback(key) : key;
2008
- value = options.valueCallback ? options.valueCallback(value) : value;
2009
- var rest = string.slice(matchedString.length);
2010
- return {
2011
- value: value,
2012
- rest: rest
2013
- };
2014
- };
2015
- }
2016
-
2017
- function findKey(object, predicate) {
2018
- for (var key in object) {
2019
- if (object.hasOwnProperty(key) && predicate(object[key])) {
2020
- return key;
2021
- }
2022
- }
2023
-
2024
- return undefined;
2025
- }
2026
-
2027
- function findIndex(array, predicate) {
2028
- for (var key = 0; key < array.length; key++) {
2029
- if (predicate(array[key])) {
2030
- return key;
2031
- }
2032
- }
2033
-
2034
- return undefined;
2035
- }
2036
-
2037
- function buildMatchPatternFn(args) {
2038
- return function (string) {
2039
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2040
- var matchResult = string.match(args.matchPattern);
2041
- if (!matchResult) return null;
2042
- var matchedString = matchResult[0];
2043
- var parseResult = string.match(args.parsePattern);
2044
- if (!parseResult) return null;
2045
- var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
2046
- value = options.valueCallback ? options.valueCallback(value) : value;
2047
- var rest = string.slice(matchedString.length);
2048
- return {
2049
- value: value,
2050
- rest: rest
2051
- };
2052
- };
2053
- }
2054
-
2055
- var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
2056
- var parseOrdinalNumberPattern = /\d+/i;
2057
- var matchEraPatterns = {
2058
- narrow: /^(b|a)/i,
2059
- abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
2060
- wide: /^(before christ|before common era|anno domini|common era)/i
2061
- };
2062
- var parseEraPatterns = {
2063
- any: [/^b/i, /^(a|c)/i]
2064
- };
2065
- var matchQuarterPatterns = {
2066
- narrow: /^[1234]/i,
2067
- abbreviated: /^q[1234]/i,
2068
- wide: /^[1234](th|st|nd|rd)? quarter/i
2069
- };
2070
- var parseQuarterPatterns = {
2071
- any: [/1/i, /2/i, /3/i, /4/i]
2072
- };
2073
- var matchMonthPatterns = {
2074
- narrow: /^[jfmasond]/i,
2075
- abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
2076
- wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
2077
- };
2078
- var parseMonthPatterns = {
2079
- 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],
2080
- 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]
2081
- };
2082
- var matchDayPatterns = {
2083
- narrow: /^[smtwf]/i,
2084
- short: /^(su|mo|tu|we|th|fr|sa)/i,
2085
- abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
2086
- wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
2087
- };
2088
- var parseDayPatterns = {
2089
- narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
2090
- any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
2091
- };
2092
- var matchDayPeriodPatterns = {
2093
- narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
2094
- any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
2095
- };
2096
- var parseDayPeriodPatterns = {
2097
- any: {
2098
- am: /^a/i,
2099
- pm: /^p/i,
2100
- midnight: /^mi/i,
2101
- noon: /^no/i,
2102
- morning: /morning/i,
2103
- afternoon: /afternoon/i,
2104
- evening: /evening/i,
2105
- night: /night/i
2106
- }
2107
- };
2108
- var match = {
2109
- ordinalNumber: buildMatchPatternFn({
2110
- matchPattern: matchOrdinalNumberPattern,
2111
- parsePattern: parseOrdinalNumberPattern,
2112
- valueCallback: function valueCallback(value) {
2113
- return parseInt(value, 10);
2114
- }
2115
- }),
2116
- era: buildMatchFn({
2117
- matchPatterns: matchEraPatterns,
2118
- defaultMatchWidth: 'wide',
2119
- parsePatterns: parseEraPatterns,
2120
- defaultParseWidth: 'any'
2121
- }),
2122
- quarter: buildMatchFn({
2123
- matchPatterns: matchQuarterPatterns,
2124
- defaultMatchWidth: 'wide',
2125
- parsePatterns: parseQuarterPatterns,
2126
- defaultParseWidth: 'any',
2127
- valueCallback: function valueCallback(index) {
2128
- return index + 1;
2129
- }
2130
- }),
2131
- month: buildMatchFn({
2132
- matchPatterns: matchMonthPatterns,
2133
- defaultMatchWidth: 'wide',
2134
- parsePatterns: parseMonthPatterns,
2135
- defaultParseWidth: 'any'
2136
- }),
2137
- day: buildMatchFn({
2138
- matchPatterns: matchDayPatterns,
2139
- defaultMatchWidth: 'wide',
2140
- parsePatterns: parseDayPatterns,
2141
- defaultParseWidth: 'any'
2142
- }),
2143
- dayPeriod: buildMatchFn({
2144
- matchPatterns: matchDayPeriodPatterns,
2145
- defaultMatchWidth: 'any',
2146
- parsePatterns: parseDayPeriodPatterns,
2147
- defaultParseWidth: 'any'
2148
- })
2149
- };
2150
-
2151
- /**
2152
- * @type {Locale}
2153
- * @category Locales
2154
- * @summary English locale (United States).
2155
- * @language English
2156
- * @iso-639-2 eng
2157
- * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
2158
- * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
2159
- */
2160
- var locale = {
2161
- code: 'en-US',
2162
- formatDistance: formatDistance,
2163
- formatLong: formatLong,
2164
- formatRelative: formatRelative,
2165
- localize: localize,
2166
- match: match,
2167
- options: {
2168
- weekStartsOn: 0
2169
- /* Sunday */
2170
- ,
2171
- firstWeekContainsDate: 1
2172
- }
2173
- };
2174
-
2175
- // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
2176
- // (one of the certain letters followed by `o`)
2177
- // - (\w)\1* matches any sequences of the same letter
2178
- // - '' matches two quote characters in a row
2179
- // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
2180
- // except a single quote symbol, which ends the sequence.
2181
- // Two quote characters do not end the sequence.
2182
- // If there is no matching single quote
2183
- // then the sequence will continue until the end of the string.
2184
- // - . matches any single character unmatched by previous parts of the RegExps
2185
-
2186
- var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
2187
- // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
2188
-
2189
- var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
2190
- var escapedStringRegExp = /^'([^]*?)'?$/;
2191
- var doubleQuoteRegExp = /''/g;
2192
- var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
2193
- /**
2194
- * @name format
2195
- * @category Common Helpers
2196
- * @summary Format the date.
2197
- *
2198
- * @description
2199
- * Return the formatted date string in the given format. The result may vary by locale.
2200
- *
2201
- * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
2202
- * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2203
- *
2204
- * The characters wrapped between two single quotes characters (') are escaped.
2205
- * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
2206
- * (see the last example)
2207
- *
2208
- * Format of the string is based on Unicode Technical Standard #35:
2209
- * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
2210
- * with a few additions (see note 7 below the table).
2211
- *
2212
- * Accepted patterns:
2213
- * | Unit | Pattern | Result examples | Notes |
2214
- * |---------------------------------|---------|-----------------------------------|-------|
2215
- * | Era | G..GGG | AD, BC | |
2216
- * | | GGGG | Anno Domini, Before Christ | 2 |
2217
- * | | GGGGG | A, B | |
2218
- * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
2219
- * | | yo | 44th, 1st, 0th, 17th | 5,7 |
2220
- * | | yy | 44, 01, 00, 17 | 5 |
2221
- * | | yyy | 044, 001, 1900, 2017 | 5 |
2222
- * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
2223
- * | | yyyyy | ... | 3,5 |
2224
- * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
2225
- * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
2226
- * | | YY | 44, 01, 00, 17 | 5,8 |
2227
- * | | YYY | 044, 001, 1900, 2017 | 5 |
2228
- * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
2229
- * | | YYYYY | ... | 3,5 |
2230
- * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
2231
- * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
2232
- * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
2233
- * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
2234
- * | | RRRRR | ... | 3,5,7 |
2235
- * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
2236
- * | | uu | -43, 01, 1900, 2017 | 5 |
2237
- * | | uuu | -043, 001, 1900, 2017 | 5 |
2238
- * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
2239
- * | | uuuuu | ... | 3,5 |
2240
- * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
2241
- * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
2242
- * | | QQ | 01, 02, 03, 04 | |
2243
- * | | QQQ | Q1, Q2, Q3, Q4 | |
2244
- * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
2245
- * | | QQQQQ | 1, 2, 3, 4 | 4 |
2246
- * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
2247
- * | | qo | 1st, 2nd, 3rd, 4th | 7 |
2248
- * | | qq | 01, 02, 03, 04 | |
2249
- * | | qqq | Q1, Q2, Q3, Q4 | |
2250
- * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
2251
- * | | qqqqq | 1, 2, 3, 4 | 4 |
2252
- * | Month (formatting) | M | 1, 2, ..., 12 | |
2253
- * | | Mo | 1st, 2nd, ..., 12th | 7 |
2254
- * | | MM | 01, 02, ..., 12 | |
2255
- * | | MMM | Jan, Feb, ..., Dec | |
2256
- * | | MMMM | January, February, ..., December | 2 |
2257
- * | | MMMMM | J, F, ..., D | |
2258
- * | Month (stand-alone) | L | 1, 2, ..., 12 | |
2259
- * | | Lo | 1st, 2nd, ..., 12th | 7 |
2260
- * | | LL | 01, 02, ..., 12 | |
2261
- * | | LLL | Jan, Feb, ..., Dec | |
2262
- * | | LLLL | January, February, ..., December | 2 |
2263
- * | | LLLLL | J, F, ..., D | |
2264
- * | Local week of year | w | 1, 2, ..., 53 | |
2265
- * | | wo | 1st, 2nd, ..., 53th | 7 |
2266
- * | | ww | 01, 02, ..., 53 | |
2267
- * | ISO week of year | I | 1, 2, ..., 53 | 7 |
2268
- * | | Io | 1st, 2nd, ..., 53th | 7 |
2269
- * | | II | 01, 02, ..., 53 | 7 |
2270
- * | Day of month | d | 1, 2, ..., 31 | |
2271
- * | | do | 1st, 2nd, ..., 31st | 7 |
2272
- * | | dd | 01, 02, ..., 31 | |
2273
- * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
2274
- * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
2275
- * | | DD | 01, 02, ..., 365, 366 | 9 |
2276
- * | | DDD | 001, 002, ..., 365, 366 | |
2277
- * | | DDDD | ... | 3 |
2278
- * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
2279
- * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
2280
- * | | EEEEE | M, T, W, T, F, S, S | |
2281
- * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
2282
- * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
2283
- * | | io | 1st, 2nd, ..., 7th | 7 |
2284
- * | | ii | 01, 02, ..., 07 | 7 |
2285
- * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
2286
- * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
2287
- * | | iiiii | M, T, W, T, F, S, S | 7 |
2288
- * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
2289
- * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
2290
- * | | eo | 2nd, 3rd, ..., 1st | 7 |
2291
- * | | ee | 02, 03, ..., 01 | |
2292
- * | | eee | Mon, Tue, Wed, ..., Sun | |
2293
- * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
2294
- * | | eeeee | M, T, W, T, F, S, S | |
2295
- * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
2296
- * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
2297
- * | | co | 2nd, 3rd, ..., 1st | 7 |
2298
- * | | cc | 02, 03, ..., 01 | |
2299
- * | | ccc | Mon, Tue, Wed, ..., Sun | |
2300
- * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
2301
- * | | ccccc | M, T, W, T, F, S, S | |
2302
- * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
2303
- * | AM, PM | a..aa | AM, PM | |
2304
- * | | aaa | am, pm | |
2305
- * | | aaaa | a.m., p.m. | 2 |
2306
- * | | aaaaa | a, p | |
2307
- * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
2308
- * | | bbb | am, pm, noon, midnight | |
2309
- * | | bbbb | a.m., p.m., noon, midnight | 2 |
2310
- * | | bbbbb | a, p, n, mi | |
2311
- * | Flexible day period | B..BBB | at night, in the morning, ... | |
2312
- * | | BBBB | at night, in the morning, ... | 2 |
2313
- * | | BBBBB | at night, in the morning, ... | |
2314
- * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
2315
- * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
2316
- * | | hh | 01, 02, ..., 11, 12 | |
2317
- * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
2318
- * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
2319
- * | | HH | 00, 01, 02, ..., 23 | |
2320
- * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
2321
- * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
2322
- * | | KK | 01, 02, ..., 11, 00 | |
2323
- * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
2324
- * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
2325
- * | | kk | 24, 01, 02, ..., 23 | |
2326
- * | Minute | m | 0, 1, ..., 59 | |
2327
- * | | mo | 0th, 1st, ..., 59th | 7 |
2328
- * | | mm | 00, 01, ..., 59 | |
2329
- * | Second | s | 0, 1, ..., 59 | |
2330
- * | | so | 0th, 1st, ..., 59th | 7 |
2331
- * | | ss | 00, 01, ..., 59 | |
2332
- * | Fraction of second | S | 0, 1, ..., 9 | |
2333
- * | | SS | 00, 01, ..., 99 | |
2334
- * | | SSS | 000, 001, ..., 999 | |
2335
- * | | SSSS | ... | 3 |
2336
- * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
2337
- * | | XX | -0800, +0530, Z | |
2338
- * | | XXX | -08:00, +05:30, Z | |
2339
- * | | XXXX | -0800, +0530, Z, +123456 | 2 |
2340
- * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
2341
- * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
2342
- * | | xx | -0800, +0530, +0000 | |
2343
- * | | xxx | -08:00, +05:30, +00:00 | 2 |
2344
- * | | xxxx | -0800, +0530, +0000, +123456 | |
2345
- * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
2346
- * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
2347
- * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
2348
- * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
2349
- * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
2350
- * | Seconds timestamp | t | 512969520 | 7 |
2351
- * | | tt | ... | 3,7 |
2352
- * | Milliseconds timestamp | T | 512969520900 | 7 |
2353
- * | | TT | ... | 3,7 |
2354
- * | Long localized date | P | 04/29/1453 | 7 |
2355
- * | | PP | Apr 29, 1453 | 7 |
2356
- * | | PPP | April 29th, 1453 | 7 |
2357
- * | | PPPP | Friday, April 29th, 1453 | 2,7 |
2358
- * | Long localized time | p | 12:00 AM | 7 |
2359
- * | | pp | 12:00:00 AM | 7 |
2360
- * | | ppp | 12:00:00 AM GMT+2 | 7 |
2361
- * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
2362
- * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
2363
- * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
2364
- * | | PPPppp | April 29th, 1453 at ... | 7 |
2365
- * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
2366
- * Notes:
2367
- * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2368
- * are the same as "stand-alone" units, but are different in some languages.
2369
- * "Formatting" units are declined according to the rules of the language
2370
- * in the context of a date. "Stand-alone" units are always nominative singular:
2371
- *
2372
- * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2373
- *
2374
- * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2375
- *
2376
- * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2377
- * the single quote characters (see below).
2378
- * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2379
- * the output will be the same as default pattern for this unit, usually
2380
- * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2381
- * are marked with "2" in the last column of the table.
2382
- *
2383
- * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2384
- *
2385
- * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2386
- *
2387
- * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2388
- *
2389
- * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2390
- *
2391
- * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2392
- *
2393
- * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2394
- * The output will be padded with zeros to match the length of the pattern.
2395
- *
2396
- * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2397
- *
2398
- * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2399
- * These tokens represent the shortest form of the quarter.
2400
- *
2401
- * 5. The main difference between `y` and `u` patterns are B.C. years:
2402
- *
2403
- * | Year | `y` | `u` |
2404
- * |------|-----|-----|
2405
- * | AC 1 | 1 | 1 |
2406
- * | BC 1 | 1 | 0 |
2407
- * | BC 2 | 2 | -1 |
2408
- *
2409
- * Also `yy` always returns the last two digits of a year,
2410
- * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2411
- *
2412
- * | Year | `yy` | `uu` |
2413
- * |------|------|------|
2414
- * | 1 | 01 | 01 |
2415
- * | 14 | 14 | 14 |
2416
- * | 376 | 76 | 376 |
2417
- * | 1453 | 53 | 1453 |
2418
- *
2419
- * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2420
- * except local week-numbering years are dependent on `options.weekStartsOn`
2421
- * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
2422
- * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
2423
- *
2424
- * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2425
- * so right now these tokens fall back to GMT timezones.
2426
- *
2427
- * 7. These patterns are not in the Unicode Technical Standard #35:
2428
- * - `i`: ISO day of week
2429
- * - `I`: ISO week of year
2430
- * - `R`: ISO week-numbering year
2431
- * - `t`: seconds timestamp
2432
- * - `T`: milliseconds timestamp
2433
- * - `o`: ordinal number modifier
2434
- * - `P`: long localized date
2435
- * - `p`: long localized time
2436
- *
2437
- * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2438
- * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2439
- *
2440
- * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2441
- * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2442
- *
2443
- * @param {Date|Number} date - the original date
2444
- * @param {String} format - the string of tokens
2445
- * @param {Object} [options] - an object with options.
2446
- * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
2447
- * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
2448
- * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
2449
- * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
2450
- * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2451
- * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
2452
- * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2453
- * @returns {String} the formatted date string
2454
- * @throws {TypeError} 2 arguments required
2455
- * @throws {RangeError} `date` must not be Invalid Date
2456
- * @throws {RangeError} `options.locale` must contain `localize` property
2457
- * @throws {RangeError} `options.locale` must contain `formatLong` property
2458
- * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
2459
- * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
2460
- * @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
2461
- * @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
2462
- * @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
2463
- * @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
2464
- * @throws {RangeError} format string contains an unescaped latin alphabet character
2465
- *
2466
- * @example
2467
- * // Represent 11 February 2014 in middle-endian format:
2468
- * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2469
- * //=> '02/11/2014'
2470
- *
2471
- * @example
2472
- * // Represent 2 July 2014 in Esperanto:
2473
- * import { eoLocale } from 'date-fns/locale/eo'
2474
- * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2475
- * locale: eoLocale
2476
- * })
2477
- * //=> '2-a de julio 2014'
2478
- *
2479
- * @example
2480
- * // Escape string by single quote characters:
2481
- * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2482
- * //=> "3 o'clock"
2483
- */
2484
-
2485
- function format(dirtyDate, dirtyFormatStr, options) {
2486
- 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;
2487
-
2488
- requiredArgs(2, arguments);
2489
- var formatStr = String(dirtyFormatStr);
2490
- var defaultOptions = getDefaultOptions();
2491
- var locale$1 = (_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 : locale;
2492
- 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); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
2493
-
2494
- if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
2495
- throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
2496
- }
2497
-
2498
- 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); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
2499
-
2500
- if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
2501
- throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
2502
- }
2503
-
2504
- if (!locale$1.localize) {
2505
- throw new RangeError('locale must contain localize property');
2506
- }
2507
-
2508
- if (!locale$1.formatLong) {
2509
- throw new RangeError('locale must contain formatLong property');
2510
- }
2511
-
2512
- var originalDate = toDate(dirtyDate);
2513
-
2514
- if (!isValid(originalDate)) {
2515
- throw new RangeError('Invalid time value');
2516
- } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
2517
- // This ensures that when UTC functions will be implemented, locales will be compatible with them.
2518
- // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
2519
-
2520
-
2521
- var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
2522
- var utcDate = subMilliseconds(originalDate, timezoneOffset);
2523
- var formatterOptions = {
2524
- firstWeekContainsDate: firstWeekContainsDate,
2525
- weekStartsOn: weekStartsOn,
2526
- locale: locale$1,
2527
- _originalDate: originalDate
2528
- };
2529
- var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
2530
- var firstCharacter = substring[0];
2531
-
2532
- if (firstCharacter === 'p' || firstCharacter === 'P') {
2533
- var longFormatter = longFormatters[firstCharacter];
2534
- return longFormatter(substring, locale$1.formatLong);
2535
- }
2536
-
2537
- return substring;
2538
- }).join('').match(formattingTokensRegExp).map(function (substring) {
2539
- // Replace two single quote characters with one single quote character
2540
- if (substring === "''") {
2541
- return "'";
2542
- }
2543
-
2544
- var firstCharacter = substring[0];
2545
-
2546
- if (firstCharacter === "'") {
2547
- return cleanEscapedString(substring);
2548
- }
2549
-
2550
- var formatter = formatters[firstCharacter];
2551
-
2552
- if (formatter) {
2553
- if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
2554
- throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2555
- }
2556
-
2557
- if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
2558
- throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2559
- }
2560
-
2561
- return formatter(utcDate, substring, locale$1.localize, formatterOptions);
2562
- }
2563
-
2564
- if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2565
- throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
2566
- }
2567
-
2568
- return substring;
2569
- }).join('');
2570
- return result;
2571
- }
2572
-
2573
- function cleanEscapedString(input) {
2574
- var matched = input.match(escapedStringRegExp);
2575
-
2576
- if (!matched) {
2577
- return input;
2578
- }
2579
-
2580
- return matched[1].replace(doubleQuoteRegExp, "'");
2581
- }
2582
-
2583
- /**
2584
- * Default values for all Dinero objects.
2585
- *
2586
- * You can override default values for all subsequent Dinero objects by changing them directly on the global `Dinero` object.
2587
- * Existing instances won't be affected.
2588
- *
2589
- * @property {Number} defaultAmount - The default amount for new Dinero objects (see {@link module:Dinero Dinero} for format).
2590
- * @property {String} defaultCurrency - The default currency for new Dinero objects (see {@link module:Dinero Dinero} for format).
2591
- * @property {Number} defaultPrecision - The default precision for new Dinero objects (see {@link module:Dinero Dinero} for format).
2592
- *
2593
- * @example
2594
- * // Will set currency to 'EUR' for all Dinero objects.
2595
- * Dinero.defaultCurrency = 'EUR'
2596
- *
2597
- * @type {Object}
2598
- */
2599
- var Defaults = {
2600
- defaultAmount: 0,
2601
- defaultCurrency: 'USD',
2602
- defaultPrecision: 2
2603
- };
2604
- /**
2605
- * Global settings for all Dinero objects.
2606
- *
2607
- * You can override global values for all subsequent Dinero objects by changing them directly on the global `Dinero` object.
2608
- * Existing instances won't be affected.
2609
- *
2610
- * @property {String} globalLocale - The global locale for new Dinero objects (see {@link module:Dinero~setLocale setLocale} for format).
2611
- * @property {String} globalFormat - The global format for new Dinero objects (see {@link module:Dinero~toFormat toFormat} for format).
2612
- * @property {String} globalRoundingMode - The global rounding mode for new Dinero objects (see {@link module:Dinero~multiply multiply} or {@link module:Dinero~divide divide} for format).
2613
- * @property {String} globalFormatRoundingMode - The global rounding mode to format new Dinero objects (see {@link module:Dinero~toFormat toFormat} or {@link module:Dinero~toRoundedUnit toRoundedUnit} for format).
2614
- * @property {(String|Promise)} globalExchangeRatesApi.endpoint - The global exchange rate API endpoint for new Dinero objects, or the global promise that resolves to the exchanges rates (see {@link module:Dinero~convert convert} for format).
2615
- * @property {String} globalExchangeRatesApi.propertyPath - The global exchange rate API property path for new Dinero objects (see {@link module:Dinero~convert convert} for format).
2616
- * @property {Object} globalExchangeRatesApi.headers - The global exchange rate API headers for new Dinero objects (see {@link module:Dinero~convert convert} for format).
2617
- *
2618
- * @example
2619
- * // Will set locale to 'fr-FR' for all Dinero objects.
2620
- * Dinero.globalLocale = 'fr-FR'
2621
- * @example
2622
- * // Will set global exchange rate API parameters for all Dinero objects.
2623
- * Dinero.globalExchangeRatesApi = {
2624
- * endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
2625
- * propertyPath: 'data.rates.{{to}}',
2626
- * headers: {
2627
- * 'user-key': 'xxxxxxxxx'
2628
- * }
2629
- * }
2630
- *
2631
- * @type {Object}
2632
- */
2633
-
2634
- var Globals = {
2635
- globalLocale: 'en-US',
2636
- globalFormat: '$0,0.00',
2637
- globalRoundingMode: 'HALF_EVEN',
2638
- globalFormatRoundingMode: 'HALF_AWAY_FROM_ZERO',
2639
- globalExchangeRatesApi: {
2640
- endpoint: undefined,
2641
- headers: undefined,
2642
- propertyPath: undefined
2643
- }
2644
- };
2645
-
2646
- function _typeof(obj) {
2647
- "@babel/helpers - typeof";
2648
-
2649
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
2650
- _typeof = function (obj) {
2651
- return typeof obj;
2652
- };
2653
- } else {
2654
- _typeof = function (obj) {
2655
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
2656
- };
2657
- }
2658
-
2659
- return _typeof(obj);
2660
- }
2661
-
2662
- function _toArray(arr) {
2663
- return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
2664
- }
2665
-
2666
- function _arrayWithHoles(arr) {
2667
- if (Array.isArray(arr)) return arr;
2668
- }
2669
-
2670
- function _iterableToArray(iter) {
2671
- if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
2672
- }
2673
-
2674
- function _unsupportedIterableToArray(o, minLen) {
2675
- if (!o) return;
2676
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
2677
- var n = Object.prototype.toString.call(o).slice(8, -1);
2678
- if (n === "Object" && o.constructor) n = o.constructor.name;
2679
- if (n === "Map" || n === "Set") return Array.from(o);
2680
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
2681
- }
2682
-
2683
- function _arrayLikeToArray(arr, len) {
2684
- if (len == null || len > arr.length) len = arr.length;
2685
-
2686
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
2687
-
2688
- return arr2;
2689
- }
2690
-
2691
- function _nonIterableRest() {
2692
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2693
- }
2694
-
2695
- /**
2696
- * Static methods for Dinero.
2697
- * @ignore
2698
- *
2699
- * @type {Object}
2700
- */
2701
- var Static = {
2702
- /**
2703
- * Returns an array of Dinero objects, normalized to the same precision (the highest).
2704
- *
2705
- * @memberof module:Dinero
2706
- * @method
2707
- *
2708
- * @param {Dinero[]} objects - An array of Dinero objects
2709
- *
2710
- * @example
2711
- * // returns an array of Dinero objects
2712
- * // both with a precision of 3
2713
- * // and an amount of 1000
2714
- * Dinero.normalizePrecision([
2715
- * Dinero({ amount: 100, precision: 2 }),
2716
- * Dinero({ amount: 1000, precision: 3 })
2717
- * ])
2718
- *
2719
- * @return {Dinero[]}
2720
- */
2721
- normalizePrecision: function normalizePrecision(objects) {
2722
- var highestPrecision = objects.reduce(function (a, b) {
2723
- return Math.max(a.getPrecision(), b.getPrecision());
2724
- });
2725
- return objects.map(function (object) {
2726
- return object.getPrecision() !== highestPrecision ? object.convertPrecision(highestPrecision) : object;
2727
- });
2728
- },
2729
-
2730
- /**
2731
- * Returns the smallest Dinero object from an array of Dinero objects
2732
- *
2733
- * @memberof module:Dinero
2734
- * @method
2735
- *
2736
- * @param {Dinero[]} objects - An array of Dinero objects
2737
- *
2738
- * @example
2739
- * // returns the smallest Dinero object with amount of 500 from an array of Dinero objects with different precisions
2740
- * Dinero.minimum([
2741
- * Dinero({ amount: 500, precision: 3 }),
2742
- * Dinero({ amount: 100, precision: 2 })
2743
- * ])
2744
- * @example
2745
- * // returns the smallest Dinero object with amount of 50 from an array of Dinero objects
2746
- * Dinero.minimum([
2747
- * Dinero({ amount: 50 }),
2748
- * Dinero({ amount: 100 })
2749
- * ])
2750
- *
2751
- * @return {Dinero[]}
2752
- */
2753
- minimum: function minimum(objects) {
2754
- var _objects = _toArray(objects),
2755
- firstObject = _objects[0],
2756
- tailObjects = _objects.slice(1);
2757
-
2758
- var currentMinimum = firstObject;
2759
- tailObjects.forEach(function (obj) {
2760
- currentMinimum = currentMinimum.lessThan(obj) ? currentMinimum : obj;
2761
- });
2762
- return currentMinimum;
2763
- },
2764
-
2765
- /**
2766
- * Returns the biggest Dinero object from an array of Dinero objects
2767
- *
2768
- * @memberof module:Dinero
2769
- * @method
2770
- *
2771
- * @param {Dinero[]} objects - An array of Dinero objects
2772
- *
2773
- * @example
2774
- * // returns the biggest Dinero object with amount of 20, from an array of Dinero objects with different precisions
2775
- * Dinero.maximum([
2776
- * Dinero({ amount: 20, precision: 2 }),
2777
- * Dinero({ amount: 150, precision: 3 })
2778
- * ])
2779
- * @example
2780
- * // returns the biggest Dinero object with amount of 100, from an array of Dinero objects
2781
- * Dinero.maximum([
2782
- * Dinero({ amount: 100 }),
2783
- * Dinero({ amount: 50 })
2784
- * ])
2785
- *
2786
- * @return {Dinero[]}
2787
- */
2788
- maximum: function maximum(objects) {
2789
- var _objects2 = _toArray(objects),
2790
- firstObject = _objects2[0],
2791
- tailObjects = _objects2.slice(1);
2792
-
2793
- var currentMaximum = firstObject;
2794
- tailObjects.forEach(function (obj) {
2795
- currentMaximum = currentMaximum.greaterThan(obj) ? currentMaximum : obj;
2796
- });
2797
- return currentMaximum;
2798
- }
2799
- };
2800
-
2801
- /**
2802
- * Returns whether a value is numeric.
2803
- * @ignore
2804
- *
2805
- * @param {} value - The value to test.
2806
- *
2807
- * @return {Boolean}
2808
- */
2809
- function isNumeric(value) {
2810
- return !isNaN(parseInt(value)) && isFinite(value);
2811
- }
2812
- /**
2813
- * Returns whether a value is a percentage.
2814
- * @ignore
2815
- *
2816
- * @param {} percentage - The percentage to test.
2817
- *
2818
- * @return {Boolean}
2819
- */
2820
-
2821
- function isPercentage(percentage) {
2822
- return isNumeric(percentage) && percentage <= 100 && percentage >= 0;
2823
- }
2824
- /**
2825
- * Returns whether an array of ratios is valid.
2826
- * @ignore
2827
- *
2828
- * @param {} ratios - The ratios to test.
2829
- *
2830
- * @return {Boolean}
2831
- */
2832
-
2833
- function areValidRatios(ratios) {
2834
- return ratios.length > 0 && ratios.every(function (ratio) {
2835
- return ratio >= 0;
2836
- }) && ratios.some(function (ratio) {
2837
- return ratio > 0;
2838
- });
2839
- }
2840
- /**
2841
- * Returns whether a value is even.
2842
- * @ignore
2843
- *
2844
- * @param {Number} value - The value to test.
2845
- *
2846
- * @return {Boolean}
2847
- */
2848
-
2849
- function isEven(value) {
2850
- return value % 2 === 0;
2851
- }
2852
- /**
2853
- * Returns whether a value is a float.
2854
- * @ignore
2855
- *
2856
- * @param {} value - The value to test.
2857
- *
2858
- * @return {Boolean}
2859
- */
2860
-
2861
- function isFloat(value) {
2862
- return isNumeric(value) && !Number.isInteger(value);
2863
- }
2864
- /**
2865
- * Returns how many fraction digits a number has.
2866
- * @ignore
2867
- *
2868
- * @param {Number} [number=0] - The number to test.
2869
- *
2870
- * @return {Number}
2871
- */
2872
-
2873
- function countFractionDigits() {
2874
- var number = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
2875
- var stringRepresentation = number.toString();
2876
-
2877
- if (stringRepresentation.indexOf('e-') > 0) {
2878
- // It's too small for a normal string representation, e.g. 1e-7 instead of 0.00000001
2879
- return parseInt(stringRepresentation.split('e-')[1]);
2880
- } else {
2881
- var fractionDigits = stringRepresentation.split('.')[1];
2882
- return fractionDigits ? fractionDigits.length : 0;
2883
- }
2884
- }
2885
- /**
2886
- * Returns whether a number is half.
2887
- * @ignore
2888
- *
2889
- * @param {Number} number - The number to test.
2890
- *
2891
- * @return {Number}
2892
- */
2893
-
2894
- function isHalf(number) {
2895
- return Math.abs(number) % 1 === 0.5;
2896
- }
2897
- /**
2898
- * Fetches a JSON resource.
2899
- * @ignore
2900
- *
2901
- * @param {String} url - The resource to fetch.
2902
- * @param {Object} [options.headers] - The headers to pass.
2903
- *
2904
- * @throws {Error} If `request.status` is lesser than 200 or greater or equal to 400.
2905
- * @throws {Error} If network fails.
2906
- *
2907
- * @return {JSON}
2908
- */
2909
-
2910
- function getJSON(url) {
2911
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2912
- return new Promise(function (resolve, reject) {
2913
- var request = Object.assign(new XMLHttpRequest(), {
2914
- onreadystatechange: function onreadystatechange() {
2915
- if (request.readyState === 4) {
2916
- if (request.status >= 200 && request.status < 400) resolve(JSON.parse(request.responseText));else reject(new Error(request.statusText));
2917
- }
2918
- },
2919
- onerror: function onerror() {
2920
- reject(new Error('Network error'));
2921
- }
2922
- });
2923
- request.open('GET', url, true);
2924
- setXHRHeaders(request, options.headers);
2925
- request.send();
2926
- });
2927
- }
2928
- /**
2929
- * Returns an XHR object with attached headers.
2930
- * @ignore
2931
- *
2932
- * @param {XMLHttpRequest} xhr - The XHR request to set headers to.
2933
- * @param {Object} headers - The headers to set.
2934
- *
2935
- * @return {XMLHttpRequest}
2936
- */
2937
-
2938
- function setXHRHeaders(xhr) {
2939
- var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2940
-
2941
- for (var header in headers) {
2942
- xhr.setRequestHeader(header, headers[header]);
2943
- }
2944
-
2945
- return xhr;
2946
- }
2947
- /**
2948
- * Returns whether a value is undefined.
2949
- * @ignore
2950
- *
2951
- * @param {} value - The value to test.
2952
- *
2953
- * @return {Boolean}
2954
- */
2955
-
2956
- function isUndefined(value) {
2957
- return typeof value === 'undefined';
2958
- }
2959
- /**
2960
- * Returns an object flattened to one level deep.
2961
- * @ignore
2962
- *
2963
- * @param {Object} object - The object to flatten.
2964
- * @param {String} separator - The separator to use between flattened nodes.
2965
- *
2966
- * @return {Object}
2967
- */
2968
-
2969
- function flattenObject(object) {
2970
- var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
2971
- var finalObject = {};
2972
- Object.entries(object).forEach(function (item) {
2973
- if (_typeof(item[1]) === 'object') {
2974
- var flatObject = flattenObject(item[1]);
2975
- Object.entries(flatObject).forEach(function (node) {
2976
- finalObject[item[0] + separator + node[0]] = node[1];
2977
- });
2978
- } else {
2979
- finalObject[item[0]] = item[1];
2980
- }
2981
- });
2982
- return finalObject;
2983
- }
2984
- /**
2985
- * Returns whether a value is thenable.
2986
- * @ignore
2987
- *
2988
- * @param {} value - The value to test.
2989
- *
2990
- * @return {Boolean}
2991
- */
2992
-
2993
- function isThenable(value) {
2994
- return Boolean(value) && (_typeof(value) === 'object' || typeof value === 'function') && typeof value.then === 'function';
2995
- }
2996
-
2997
- function Calculator() {
2998
- var floatMultiply = function floatMultiply(a, b) {
2999
- var getFactor = function getFactor(number) {
3000
- return Math.pow(10, countFractionDigits(number));
3001
- };
3002
-
3003
- var factor = Math.max(getFactor(a), getFactor(b));
3004
- return Math.round(a * factor) * Math.round(b * factor) / (factor * factor);
3005
- };
3006
-
3007
- var roundingModes = {
3008
- HALF_ODD: function HALF_ODD(number) {
3009
- var rounded = Math.round(number);
3010
- return isHalf(number) ? isEven(rounded) ? rounded - 1 : rounded : rounded;
3011
- },
3012
- HALF_EVEN: function HALF_EVEN(number) {
3013
- var rounded = Math.round(number);
3014
- return isHalf(number) ? isEven(rounded) ? rounded : rounded - 1 : rounded;
3015
- },
3016
- HALF_UP: function HALF_UP(number) {
3017
- return Math.round(number);
3018
- },
3019
- HALF_DOWN: function HALF_DOWN(number) {
3020
- return isHalf(number) ? Math.floor(number) : Math.round(number);
3021
- },
3022
- HALF_TOWARDS_ZERO: function HALF_TOWARDS_ZERO(number) {
3023
- return isHalf(number) ? Math.sign(number) * Math.floor(Math.abs(number)) : Math.round(number);
3024
- },
3025
- HALF_AWAY_FROM_ZERO: function HALF_AWAY_FROM_ZERO(number) {
3026
- return isHalf(number) ? Math.sign(number) * Math.ceil(Math.abs(number)) : Math.round(number);
3027
- },
3028
- DOWN: function DOWN(number) {
3029
- return Math.floor(number);
3030
- }
3031
- };
3032
- return {
3033
- /**
3034
- * Returns the sum of two numbers.
3035
- * @ignore
3036
- *
3037
- * @param {Number} a - The first number to add.
3038
- * @param {Number} b - The second number to add.
3039
- *
3040
- * @return {Number}
3041
- */
3042
- add: function add(a, b) {
3043
- return a + b;
3044
- },
3045
-
3046
- /**
3047
- * Returns the difference of two numbers.
3048
- * @ignore
3049
- *
3050
- * @param {Number} a - The first number to subtract.
3051
- * @param {Number} b - The second number to subtract.
3052
- *
3053
- * @return {Number}
3054
- */
3055
- subtract: function subtract(a, b) {
3056
- return a - b;
3057
- },
3058
-
3059
- /**
3060
- * Returns the product of two numbers.
3061
- * @ignore
3062
- *
3063
- * @param {Number} a - The first number to multiply.
3064
- * @param {Number} b - The second number to multiply.
3065
- *
3066
- * @return {Number}
3067
- */
3068
- multiply: function multiply(a, b) {
3069
- return isFloat(a) || isFloat(b) ? floatMultiply(a, b) : a * b;
3070
- },
3071
-
3072
- /**
3073
- * Returns the quotient of two numbers.
3074
- * @ignore
3075
- *
3076
- * @param {Number} a - The first number to divide.
3077
- * @param {Number} b - The second number to divide.
3078
- *
3079
- * @return {Number}
3080
- */
3081
- divide: function divide(a, b) {
3082
- return a / b;
3083
- },
3084
-
3085
- /**
3086
- * Returns the remainder of two numbers.
3087
- * @ignore
3088
- *
3089
- * @param {Number} a - The first number to divide.
3090
- * @param {Number} b - The second number to divide.
3091
- *
3092
- * @return {Number}
3093
- */
3094
- modulo: function modulo(a, b) {
3095
- return a % b;
3096
- },
3097
-
3098
- /**
3099
- * Returns a rounded number based off a specific rounding mode.
3100
- * @ignore
3101
- *
3102
- * @param {Number} number - The number to round.
3103
- * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use.
3104
- *
3105
- * @returns {Number}
3106
- */
3107
- round: function round(number) {
3108
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'HALF_EVEN';
3109
- return roundingModes[roundingMode](number);
3110
- }
3111
- };
3112
- }
3113
-
3114
- var calculator = Calculator();
3115
- function Format(format) {
3116
- var matches = /^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(format);
3117
- return {
3118
- /**
3119
- * Returns the matches.
3120
- * @ignore
3121
- *
3122
- * @return {Array}
3123
- */
3124
- getMatches: function getMatches() {
3125
- return matches !== null ? matches.slice(1).filter(function (match) {
3126
- return !isUndefined(match);
3127
- }) : [];
3128
- },
3129
-
3130
- /**
3131
- * Returns the amount of fraction digits to display.
3132
- * @ignore
3133
- *
3134
- * @return {Number}
3135
- */
3136
- getMinimumFractionDigits: function getMinimumFractionDigits() {
3137
- var decimalPosition = function decimalPosition(match) {
3138
- return match === '.';
3139
- };
3140
-
3141
- return !isUndefined(this.getMatches().find(decimalPosition)) ? this.getMatches()[calculator.add(this.getMatches().findIndex(decimalPosition), 1)].split('').length : 0;
3142
- },
3143
-
3144
- /**
3145
- * Returns the currency display mode.
3146
- * @ignore
3147
- *
3148
- * @return {String}
3149
- */
3150
- getCurrencyDisplay: function getCurrencyDisplay() {
3151
- var modes = {
3152
- USD: 'code',
3153
- dollar: 'name',
3154
- $: 'symbol'
3155
- };
3156
- return modes[this.getMatches().find(function (match) {
3157
- return match === 'USD' || match === 'dollar' || match === '$';
3158
- })];
3159
- },
3160
-
3161
- /**
3162
- * Returns the formatting style.
3163
- * @ignore
3164
- *
3165
- * @return {String}
3166
- */
3167
- getStyle: function getStyle() {
3168
- return !isUndefined(this.getCurrencyDisplay(this.getMatches())) ? 'currency' : 'decimal';
3169
- },
3170
-
3171
- /**
3172
- * Returns whether grouping should be used or not.
3173
- * @ignore
3174
- *
3175
- * @return {Boolean}
3176
- */
3177
- getUseGrouping: function getUseGrouping() {
3178
- return !isUndefined(this.getMatches().find(function (match) {
3179
- return match === ',';
3180
- }));
3181
- }
3182
- };
3183
- }
3184
-
3185
- function CurrencyConverter(options) {
3186
- /* istanbul ignore next */
3187
- var mergeTags = function mergeTags() {
3188
- var string = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3189
- var tags = arguments.length > 1 ? arguments[1] : undefined;
3190
-
3191
- for (var tag in tags) {
3192
- string = string.replace("{{".concat(tag, "}}"), tags[tag]);
3193
- }
3194
-
3195
- return string;
3196
- };
3197
- /* istanbul ignore next */
3198
-
3199
-
3200
- var getRatesFromRestApi = function getRatesFromRestApi(from, to) {
3201
- return getJSON(mergeTags(options.endpoint, {
3202
- from: from,
3203
- to: to
3204
- }), {
3205
- headers: options.headers
3206
- });
3207
- };
3208
-
3209
- return {
3210
- /**
3211
- * Returns the exchange rate.
3212
- * @ignore
3213
- *
3214
- * @param {String} from - The base currency.
3215
- * @param {String} to - The destination currency.
3216
- *
3217
- * @return {Promise}
3218
- */
3219
- getExchangeRate: function getExchangeRate(from, to) {
3220
- return (isThenable(options.endpoint) ? options.endpoint : getRatesFromRestApi(from, to)).then(function (data) {
3221
- return flattenObject(data)[mergeTags(options.propertyPath, {
3222
- from: from,
3223
- to: to
3224
- })];
3225
- });
3226
- }
3227
- };
3228
- }
3229
-
3230
- /**
3231
- * Performs an assertion.
3232
- * @ignore
3233
- *
3234
- * @param {Boolean} condition - The expression to assert.
3235
- * @param {String} errorMessage - The message to throw if the assertion fails
3236
- * @param {ErrorConstructor} [ErrorType=Error] - The error to throw if the assertion fails.
3237
- *
3238
- * @throws {Error} If `condition` returns `false`.
3239
- */
3240
-
3241
- function assert(condition, errorMessage) {
3242
- var ErrorType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Error;
3243
- if (!condition) throw new ErrorType(errorMessage);
3244
- }
3245
- /**
3246
- * Asserts a value is a percentage.
3247
- * @ignore
3248
- *
3249
- * @param {} percentage - The percentage to test.
3250
- *
3251
- * @throws {RangeError} If `percentage` is out of range.
3252
- */
3253
-
3254
- function assertPercentage(percentage) {
3255
- assert(isPercentage(percentage), 'You must provide a numeric value between 0 and 100.', RangeError);
3256
- }
3257
- /**
3258
- * Asserts an array of ratios is valid.
3259
- * @ignore
3260
- *
3261
- * @param {} ratios - The ratios to test.
3262
- *
3263
- * @throws {TypeError} If `ratios` are invalid.
3264
- */
3265
-
3266
- function assertValidRatios(ratios) {
3267
- assert(areValidRatios(ratios), 'You must provide a non-empty array of numeric values greater than 0.', TypeError);
3268
- }
3269
- /**
3270
- * Asserts a value is an integer.
3271
- * @ignore
3272
- *
3273
- * @param {} number - The value to test.
3274
- *
3275
- * @throws {TypeError}
3276
- */
3277
-
3278
- function assertInteger(number) {
3279
- assert(Number.isInteger(number), 'You must provide an integer.', TypeError);
3280
- }
3281
-
3282
- var calculator$1 = Calculator();
3283
- /**
3284
- * A Dinero object is an immutable data structure representing a specific monetary value.
3285
- * It comes with methods for creating, parsing, manipulating, testing, transforming and formatting them.
3286
- *
3287
- * A Dinero object has:
3288
- *
3289
- * * An `amount`, expressed in minor currency units, as an integer.
3290
- * * A `currency`, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
3291
- * * A `precision`, expressed as an integer, to represent the number of decimal places in the `amount`.
3292
- * This is helpful when you want to represent fractional minor currency units (e.g.: $10.4545).
3293
- * You can also use it to represent a currency with a different [exponent](https://en.wikipedia.org/wiki/ISO_4217#Treatment_of_minor_currency_units_.28the_.22exponent.22.29) than `2` (e.g.: Iraqi dinar with 1000 fils in 1 dinar (exponent of `3`), Japanese yen with no sub-units (exponent of `0`)).
3294
- * * An optional `locale` property that affects how output strings are formatted.
3295
- *
3296
- * Here's an overview of the public API:
3297
- *
3298
- * * **Access:** {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~getCurrency getCurrency}, {@link module:Dinero~getLocale getLocale} and {@link module:Dinero~getPrecision getPrecision}.
3299
- * * **Manipulation:** {@link module:Dinero~add add}, {@link module:Dinero~subtract subtract}, {@link module:Dinero~multiply multiply}, {@link module:Dinero~divide divide}, {@link module:Dinero~percentage percentage}, {@link module:Dinero~allocate allocate} and {@link module:Dinero~convert convert}.
3300
- * * **Testing:** {@link module:Dinero~equalsTo equalsTo}, {@link module:Dinero~lessThan lessThan}, {@link module:Dinero~lessThanOrEqual lessThanOrEqual}, {@link module:Dinero~greaterThan greaterThan}, {@link module:Dinero~greaterThanOrEqual greaterThanOrEqual}, {@link module:Dinero~isZero isZero}, {@link module:Dinero~isPositive isPositive}, {@link module:Dinero~isNegative isNegative}, {@link module:Dinero~hasSubUnits hasSubUnits}, {@link module:Dinero~hasSameCurrency hasSameCurrency} and {@link module:Dinero~hasSameAmount hasSameAmount}.
3301
- * * **Configuration:** {@link module:Dinero~setLocale setLocale}.
3302
- * * **Conversion & formatting:** {@link module:Dinero~toFormat toFormat}, {@link module:Dinero~toUnit toUnit}, {@link module:Dinero~toRoundedUnit toRoundedUnit}, {@link module:Dinero~toObject toObject}, {@link module:Dinero~toJSON toJSON}, {@link module:Dinero~convertPrecision convertPrecision} and {@link module:Dinero.normalizePrecision normalizePrecision}.
3303
- *
3304
- * Dinero.js uses `number`s under the hood, so it's constrained by the [double-precision floating-point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). Using values over [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER) or below [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MIN_SAFE_INTEGER) will yield unpredictable results.
3305
- * Same goes with performing calculations: once the internal `amount` value exceeds those limits, precision is no longer guaranteed.
3306
- *
3307
- * @module Dinero
3308
- * @param {Number} [options.amount=0] - The amount in minor currency units (as an integer).
3309
- * @param {String} [options.currency='USD'] - An ISO 4217 currency code.
3310
- * @param {String} [options.precision=2] - The number of decimal places to represent.
3311
- *
3312
- * @throws {TypeError} If `amount` or `precision` is invalid. Integers over [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER) or below [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MIN_SAFE_INTEGER) are considered valid, even though they can lead to imprecise amounts.
3313
- *
3314
- * @return {Object}
3315
- */
3316
-
3317
- var Dinero = function Dinero(options) {
3318
- var _Object$assign = Object.assign({}, {
3319
- amount: Dinero.defaultAmount,
3320
- currency: Dinero.defaultCurrency,
3321
- precision: Dinero.defaultPrecision
3322
- }, options),
3323
- amount = _Object$assign.amount,
3324
- currency = _Object$assign.currency,
3325
- precision = _Object$assign.precision;
3326
-
3327
- assertInteger(amount);
3328
- assertInteger(precision);
3329
- var globalLocale = Dinero.globalLocale,
3330
- globalFormat = Dinero.globalFormat,
3331
- globalRoundingMode = Dinero.globalRoundingMode,
3332
- globalFormatRoundingMode = Dinero.globalFormatRoundingMode;
3333
- var globalExchangeRatesApi = Object.assign({}, Dinero.globalExchangeRatesApi);
3334
- /**
3335
- * Uses ES5 function notation so `this` can be passed through call, apply and bind
3336
- * @ignore
3337
- */
3338
-
3339
- var create = function create(options) {
3340
- var obj = Object.assign({}, Object.assign({}, {
3341
- amount: amount,
3342
- currency: currency,
3343
- precision: precision
3344
- }, options), Object.assign({}, {
3345
- locale: this.locale
3346
- }, options));
3347
- return Object.assign(Dinero({
3348
- amount: obj.amount,
3349
- currency: obj.currency,
3350
- precision: obj.precision
3351
- }), {
3352
- locale: obj.locale
3353
- });
3354
- };
3355
- /**
3356
- * Uses ES5 function notation so `this` can be passed through call, apply and bind
3357
- * @ignore
3358
- */
3359
-
3360
-
3361
- var assertSameCurrency = function assertSameCurrency(comparator) {
3362
- assert(this.hasSameCurrency(comparator), 'You must provide a Dinero instance with the same currency.', TypeError);
3363
- };
3364
-
3365
- return {
3366
- /**
3367
- * Returns the amount.
3368
- *
3369
- * @example
3370
- * // returns 500
3371
- * Dinero({ amount: 500 }).getAmount()
3372
- *
3373
- * @return {Number}
3374
- */
3375
- getAmount: function getAmount() {
3376
- return amount;
3377
- },
3378
-
3379
- /**
3380
- * Returns the currency.
3381
- *
3382
- * @example
3383
- * // returns 'EUR'
3384
- * Dinero({ currency: 'EUR' }).getCurrency()
3385
- *
3386
- * @return {String}
3387
- */
3388
- getCurrency: function getCurrency() {
3389
- return currency;
3390
- },
3391
-
3392
- /**
3393
- * Returns the locale.
3394
- *
3395
- * @example
3396
- * // returns 'fr-FR'
3397
- * Dinero().setLocale('fr-FR').getLocale()
3398
- *
3399
- * @return {String}
3400
- */
3401
- getLocale: function getLocale() {
3402
- return this.locale || globalLocale;
3403
- },
3404
-
3405
- /**
3406
- * Returns a new Dinero object with an embedded locale.
3407
- *
3408
- * @param {String} newLocale - The new locale as an {@link http://tools.ietf.org/html/rfc5646 BCP 47 language tag}.
3409
- *
3410
- * @example
3411
- * // Returns a Dinero object with locale 'ja-JP'
3412
- * Dinero().setLocale('ja-JP')
3413
- *
3414
- * @return {Dinero}
3415
- */
3416
- setLocale: function setLocale(newLocale) {
3417
- return create.call(this, {
3418
- locale: newLocale
3419
- });
3420
- },
3421
-
3422
- /**
3423
- * Returns the precision.
3424
- *
3425
- * @example
3426
- * // returns 3
3427
- * Dinero({ precision: 3 }).getPrecision()
3428
- *
3429
- * @return {Number}
3430
- */
3431
- getPrecision: function getPrecision() {
3432
- return precision;
3433
- },
3434
-
3435
- /**
3436
- * Returns a new Dinero object with a new precision and a converted amount.
3437
- *
3438
- * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3439
- * This can be necessary when you need to convert objects to a smaller precision.
3440
- *
3441
- * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent conversions for safer results.
3442
- * You can also specify a different `roundingMode` to better fit your needs.
3443
- *
3444
- * @param {Number} newPrecision - The new precision.
3445
- * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3446
- *
3447
- * @example
3448
- * // Returns a Dinero object with precision 3 and amount 1000
3449
- * Dinero({ amount: 100, precision: 2 }).convertPrecision(3)
3450
- *
3451
- * @throws {TypeError} If `newPrecision` is invalid.
3452
- *
3453
- * @return {Dinero}
3454
- */
3455
- convertPrecision: function convertPrecision(newPrecision) {
3456
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
3457
- assertInteger(newPrecision);
3458
- var precision = this.getPrecision();
3459
- var isNewPrecisionLarger = newPrecision > precision;
3460
- var operation = isNewPrecisionLarger ? calculator$1.multiply : calculator$1.divide;
3461
- var terms = isNewPrecisionLarger ? [newPrecision, precision] : [precision, newPrecision];
3462
- var factor = Math.pow(10, calculator$1.subtract.apply(calculator$1, terms));
3463
- return create.call(this, {
3464
- amount: calculator$1.round(operation(this.getAmount(), factor), roundingMode),
3465
- precision: newPrecision
3466
- });
3467
- },
3468
-
3469
- /**
3470
- * Returns a new Dinero object that represents the sum of this and an other Dinero object.
3471
- *
3472
- * If Dinero objects have a different `precision`, they will be first converted to the highest.
3473
- *
3474
- * @param {Dinero} addend - The Dinero object to add.
3475
- *
3476
- * @example
3477
- * // returns a Dinero object with amount 600
3478
- * Dinero({ amount: 400 }).add(Dinero({ amount: 200 }))
3479
- * @example
3480
- * // returns a Dinero object with amount 144545 and precision 4
3481
- * Dinero({ amount: 400 }).add(Dinero({ amount: 104545, precision: 4 }))
3482
- *
3483
- * @throws {TypeError} If `addend` has a different currency.
3484
- *
3485
- * @return {Dinero}
3486
- */
3487
- add: function add(addend) {
3488
- assertSameCurrency.call(this, addend);
3489
- var addends = Dinero.normalizePrecision([this, addend]);
3490
- return create.call(this, {
3491
- amount: calculator$1.add(addends[0].getAmount(), addends[1].getAmount()),
3492
- precision: addends[0].getPrecision()
3493
- });
3494
- },
3495
-
3496
- /**
3497
- * Returns a new Dinero object that represents the difference of this and an other Dinero object.
3498
- *
3499
- * If Dinero objects have a different `precision`, they will be first converted to the highest.
3500
- *
3501
- * @param {Dinero} subtrahend - The Dinero object to subtract.
3502
- *
3503
- * @example
3504
- * // returns a Dinero object with amount 200
3505
- * Dinero({ amount: 400 }).subtract(Dinero({ amount: 200 }))
3506
- * @example
3507
- * // returns a Dinero object with amount 64545 and precision 4
3508
- * Dinero({ amount: 104545, precision: 4 }).subtract(Dinero({ amount: 400 }))
3509
- *
3510
- * @throws {TypeError} If `subtrahend` has a different currency.
3511
- *
3512
- * @return {Dinero}
3513
- */
3514
- subtract: function subtract(subtrahend) {
3515
- assertSameCurrency.call(this, subtrahend);
3516
- var subtrahends = Dinero.normalizePrecision([this, subtrahend]);
3517
- return create.call(this, {
3518
- amount: calculator$1.subtract(subtrahends[0].getAmount(), subtrahends[1].getAmount()),
3519
- precision: subtrahends[0].getPrecision()
3520
- });
3521
- },
3522
-
3523
- /**
3524
- * Returns a new Dinero object that represents the multiplied value by the given factor.
3525
- *
3526
- * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3527
- *
3528
- * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
3529
- * You can also specify a different `roundingMode` to better fit your needs.
3530
- *
3531
- * @param {Number} multiplier - The factor to multiply by.
3532
- * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3533
- *
3534
- * @example
3535
- * // returns a Dinero object with amount 1600
3536
- * Dinero({ amount: 400 }).multiply(4)
3537
- * @example
3538
- * // returns a Dinero object with amount 800
3539
- * Dinero({ amount: 400 }).multiply(2.001)
3540
- * @example
3541
- * // returns a Dinero object with amount 801
3542
- * Dinero({ amount: 400 }).multiply(2.00125, 'HALF_UP')
3543
- *
3544
- * @return {Dinero}
3545
- */
3546
- multiply: function multiply(multiplier) {
3547
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3548
- return create.call(this, {
3549
- amount: calculator$1.round(calculator$1.multiply(this.getAmount(), multiplier), roundingMode)
3550
- });
3551
- },
3552
-
3553
- /**
3554
- * Returns a new Dinero object that represents the divided value by the given factor.
3555
- *
3556
- * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3557
- *
3558
- * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
3559
- * You can also specify a different `roundingMode` to better fit your needs.
3560
- *
3561
- * As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
3562
- *
3563
- * @param {Number} divisor - The factor to divide by.
3564
- * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3565
- *
3566
- * @example
3567
- * // returns a Dinero object with amount 100
3568
- * Dinero({ amount: 400 }).divide(4)
3569
- * @example
3570
- * // returns a Dinero object with amount 52
3571
- * Dinero({ amount: 105 }).divide(2)
3572
- * @example
3573
- * // returns a Dinero object with amount 53
3574
- * Dinero({ amount: 105 }).divide(2, 'HALF_UP')
3575
- *
3576
- * @return {Dinero}
3577
- */
3578
- divide: function divide(divisor) {
3579
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3580
- return create.call(this, {
3581
- amount: calculator$1.round(calculator$1.divide(this.getAmount(), divisor), roundingMode)
3582
- });
3583
- },
3584
-
3585
- /**
3586
- * Returns a new Dinero object that represents a percentage of this.
3587
- *
3588
- * As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
3589
- *
3590
- * @param {Number} percentage - The percentage to extract (between 0 and 100).
3591
- * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3592
- *
3593
- * @example
3594
- * // returns a Dinero object with amount 5000
3595
- * Dinero({ amount: 10000 }).percentage(50)
3596
- * @example
3597
- * // returns a Dinero object with amount 29
3598
- * Dinero({ amount: 57 }).percentage(50, "HALF_ODD")
3599
- *
3600
- * @throws {RangeError} If `percentage` is out of range.
3601
- *
3602
- * @return {Dinero}
3603
- */
3604
- percentage: function percentage(_percentage) {
3605
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3606
- assertPercentage(_percentage);
3607
- return this.multiply(calculator$1.divide(_percentage, 100), roundingMode);
3608
- },
3609
-
3610
- /**
3611
- * Allocates the amount of a Dinero object according to a list of ratios.
3612
- *
3613
- * Sometimes you need to split monetary values but percentages can't cut it without adding or losing pennies.
3614
- * A good example is invoicing: let's say you need to bill $1,000.03 and you want a 50% downpayment.
3615
- * If you use {@link module:Dinero~percentage percentage}, you'll get an accurate Dinero object but the amount won't be billable: you can't split a penny.
3616
- * If you round it, you'll bill a penny extra.
3617
- * With {@link module:Dinero~allocate allocate}, you can split a monetary amount then distribute the remainder as evenly as possible.
3618
- *
3619
- * You can use percentage style or ratio style for `ratios`: `[25, 75]` and `[1, 3]` will do the same thing.
3620
- *
3621
- * Since v1.8.0, you can use zero ratios (such as [0, 50, 50]). If there's a remainder to distribute, zero ratios are skipped and return a Dinero object with amount zero.
3622
- *
3623
- * @param {Number[]} ratios - The ratios to allocate the money to.
3624
- *
3625
- * @example
3626
- * // returns an array of two Dinero objects
3627
- * // the first one with an amount of 502
3628
- * // the second one with an amount of 501
3629
- * Dinero({ amount: 1003 }).allocate([50, 50])
3630
- * @example
3631
- * // returns an array of two Dinero objects
3632
- * // the first one with an amount of 25
3633
- * // the second one with an amount of 75
3634
- * Dinero({ amount: 100 }).allocate([1, 3])
3635
- * @example
3636
- * // since version 1.8.0
3637
- * // returns an array of three Dinero objects
3638
- * // the first one with an amount of 0
3639
- * // the second one with an amount of 502
3640
- * // the third one with an amount of 501
3641
- * Dinero({ amount: 1003 }).allocate([0, 50, 50])
3642
- *
3643
- * @throws {TypeError} If ratios are invalid.
3644
- *
3645
- * @return {Dinero[]}
3646
- */
3647
- allocate: function allocate(ratios) {
3648
- var _this = this;
3649
-
3650
- assertValidRatios(ratios);
3651
- var total = ratios.reduce(function (a, b) {
3652
- return calculator$1.add(a, b);
3653
- });
3654
- var remainder = this.getAmount();
3655
- var shares = ratios.map(function (ratio) {
3656
- var share = Math.floor(calculator$1.divide(calculator$1.multiply(_this.getAmount(), ratio), total));
3657
- remainder = calculator$1.subtract(remainder, share);
3658
- return create.call(_this, {
3659
- amount: share
3660
- });
3661
- });
3662
- var i = 0;
3663
-
3664
- while (remainder > 0) {
3665
- if (ratios[i] > 0) {
3666
- shares[i] = shares[i].add(create.call(this, {
3667
- amount: 1
3668
- }));
3669
- remainder = calculator$1.subtract(remainder, 1);
3670
- }
3671
-
3672
- i += 1;
3673
- }
3674
-
3675
- return shares;
3676
- },
3677
-
3678
- /**
3679
- * Returns a Promise containing a new Dinero object converted to another currency.
3680
- *
3681
- * You have two options to provide the exchange rates:
3682
- *
3683
- * 1. **Use an exchange rate REST API, and let Dinero handle the fetching and conversion.**
3684
- * This is a simple option if you have access to an exchange rate REST API and want Dinero to do the rest.
3685
- * 2. **Fetch the exchange rates on your own and provide them directly.**
3686
- * This is useful if you're fetching your rates from somewhere else (a file, a database), use a different protocol or query language than REST (SOAP, GraphQL) or want to fetch rates once and cache them instead of making new requests every time.
3687
- *
3688
- * **If you want to use a REST API**, you must provide a third-party endpoint yourself. Dinero doesn't come bundled with an exchange rates endpoint.
3689
- *
3690
- * Here are some exchange rate APIs you can use:
3691
- *
3692
- * * [Fixer](https://fixer.io)
3693
- * * [Open Exchange Rates](https://openexchangerates.org)
3694
- * * [Coinbase](https://api.coinbase.com/v2/exchange-rates)
3695
- * * More [foreign](https://github.com/toddmotto/public-apis#currency-exchange) and [crypto](https://github.com/toddmotto/public-apis#cryptocurrency) exchange rate APIs.
3696
- *
3697
- * **If you want to fetch your own rates and provide them directly**, you need to pass a promise that resolves to the exchanges rates.
3698
- *
3699
- * In both cases, you need to specify at least:
3700
- *
3701
- * * a **destination currency**: the currency in which you want to convert your Dinero object. You can specify it with `currency`.
3702
- * * an **endpoint**: the API URL to query exchange rates, with parameters, or a promise that resolves to the exchange rates. You can specify it with `options.endpoint`.
3703
- * * a **property path**: the path to access the wanted rate in your API's JSON response (or the custom promise's payload). For example, with a response of:
3704
- * ```json
3705
- * {
3706
- * "data": {
3707
- * "base": "USD",
3708
- * "destination": "EUR",
3709
- * "rate": "0.827728919"
3710
- * }
3711
- * }
3712
- * ```
3713
- * Then the property path is `'data.rate'`. You can specify it with `options.propertyPath`.
3714
- *
3715
- * The base currency (the one of your Dinero object) and the destination currency can be used as "merge tags" with the mustache syntax, respectively `{{from}}` and `{{to}}`.
3716
- * You can use these tags to refer to these values in `options.endpoint` and `options.propertyPath`.
3717
- *
3718
- * For example, if you need to specify the base currency as a query parameter, you can do the following:
3719
- *
3720
- * ```js
3721
- * {
3722
- * endpoint: 'https://yourexchangerates.api/latest?base={{from}}'
3723
- * }
3724
- * ```
3725
- *
3726
- * @param {String} currency - The destination currency, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
3727
- * @param {(String|Promise)} options.endpoint - The API endpoint to retrieve exchange rates. You can substitute this with a promise that resolves to the exchanges rates if you already have them.
3728
- * @param {String} [options.propertyPath='rates.{{to}}'] - The property path to the rate.
3729
- * @param {Object} [options.headers] - The HTTP headers to provide, if needed.
3730
- * @param {String} [options.roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3731
- *
3732
- * @example
3733
- * // your global API parameters
3734
- * Dinero.globalExchangeRatesApi = { ... }
3735
- *
3736
- * // returns a Promise containing a Dinero object with the destination currency
3737
- * // and the initial amount converted to the new currency.
3738
- * Dinero({ amount: 500 }).convert('EUR')
3739
- * @example
3740
- * // returns a Promise containing a Dinero object,
3741
- * // with specific API parameters and rounding mode for this specific instance.
3742
- * Dinero({ amount: 500 })
3743
- * .convert('XBT', {
3744
- * endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
3745
- * propertyPath: 'data.rates.{{to}}',
3746
- * headers: {
3747
- * 'user-key': 'xxxxxxxxx'
3748
- * },
3749
- * roundingMode: 'HALF_UP'
3750
- * })
3751
- * @example
3752
- * // usage with exchange rates provided as a custom promise
3753
- * // using the default `propertyPath` format (so it doesn't have to be specified)
3754
- * const rates = {
3755
- * rates: {
3756
- * EUR: 0.81162
3757
- * }
3758
- * }
3759
- *
3760
- * Dinero({ amount: 500 })
3761
- * .convert('EUR', {
3762
- * endpoint: new Promise(resolve => resolve(rates))
3763
- * })
3764
- * @example
3765
- * // usage with Promise.prototype.then and Promise.prototype.catch
3766
- * Dinero({ amount: 500 })
3767
- * .convert('EUR')
3768
- * .then(dinero => {
3769
- * dinero.getCurrency() // returns 'EUR'
3770
- * })
3771
- * .catch(err => {
3772
- * // handle errors
3773
- * })
3774
- * @example
3775
- * // usage with async/await
3776
- * (async () => {
3777
- * const price = await Dinero({ amount: 500 }).convert('EUR')
3778
- * price.getCurrency() // returns 'EUR'
3779
- * })()
3780
- *
3781
- * @return {Promise}
3782
- */
3783
- convert: function convert(currency) {
3784
- var _this2 = this;
3785
-
3786
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
3787
- _ref$endpoint = _ref.endpoint,
3788
- endpoint = _ref$endpoint === void 0 ? globalExchangeRatesApi.endpoint : _ref$endpoint,
3789
- _ref$propertyPath = _ref.propertyPath,
3790
- propertyPath = _ref$propertyPath === void 0 ? globalExchangeRatesApi.propertyPath || 'rates.{{to}}' : _ref$propertyPath,
3791
- _ref$headers = _ref.headers,
3792
- headers = _ref$headers === void 0 ? globalExchangeRatesApi.headers : _ref$headers,
3793
- _ref$roundingMode = _ref.roundingMode,
3794
- roundingMode = _ref$roundingMode === void 0 ? globalRoundingMode : _ref$roundingMode;
3795
-
3796
- var options = Object.assign({}, {
3797
- endpoint: endpoint,
3798
- propertyPath: propertyPath,
3799
- headers: headers,
3800
- roundingMode: roundingMode
3801
- });
3802
- return CurrencyConverter(options).getExchangeRate(this.getCurrency(), currency).then(function (rate) {
3803
- assert(!isUndefined(rate), "No rate was found for the destination currency \"".concat(currency, "\"."), TypeError);
3804
- return create.call(_this2, {
3805
- amount: calculator$1.round(calculator$1.multiply(_this2.getAmount(), parseFloat(rate)), options.roundingMode),
3806
- currency: currency
3807
- });
3808
- });
3809
- },
3810
-
3811
- /**
3812
- * Checks whether the value represented by this object equals to the other.
3813
- *
3814
- * @param {Dinero} comparator - The Dinero object to compare to.
3815
- *
3816
- * @example
3817
- * // returns true
3818
- * Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
3819
- * @example
3820
- * // returns false
3821
- * Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
3822
- * @example
3823
- * // returns false
3824
- * Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
3825
- * @example
3826
- * // returns false
3827
- * Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
3828
- * @example
3829
- * // returns true
3830
- * Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
3831
- * @example
3832
- * // returns false
3833
- * Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
3834
- *
3835
- * @return {Boolean}
3836
- */
3837
- equalsTo: function equalsTo(comparator) {
3838
- return this.hasSameAmount(comparator) && this.hasSameCurrency(comparator);
3839
- },
3840
-
3841
- /**
3842
- * Checks whether the value represented by this object is less than the other.
3843
- *
3844
- * @param {Dinero} comparator - The Dinero object to compare to.
3845
- *
3846
- * @example
3847
- * // returns true
3848
- * Dinero({ amount: 500 }).lessThan(Dinero({ amount: 800 }))
3849
- * @example
3850
- * // returns false
3851
- * Dinero({ amount: 800 }).lessThan(Dinero({ amount: 500 }))
3852
- * @example
3853
- * // returns true
3854
- * Dinero({ amount: 5000, precision: 3 }).lessThan(Dinero({ amount: 800 }))
3855
- * @example
3856
- * // returns false
3857
- * Dinero({ amount: 800 }).lessThan(Dinero({ amount: 5000, precision: 3 }))
3858
- *
3859
- * @throws {TypeError} If `comparator` has a different currency.
3860
- *
3861
- * @return {Boolean}
3862
- */
3863
- lessThan: function lessThan(comparator) {
3864
- assertSameCurrency.call(this, comparator);
3865
- var comparators = Dinero.normalizePrecision([this, comparator]);
3866
- return comparators[0].getAmount() < comparators[1].getAmount();
3867
- },
3868
-
3869
- /**
3870
- * Checks whether the value represented by this object is less than or equal to the other.
3871
- *
3872
- * @param {Dinero} comparator - The Dinero object to compare to.
3873
- *
3874
- * @example
3875
- * // returns true
3876
- * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 800 }))
3877
- * @example
3878
- * // returns true
3879
- * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 500 }))
3880
- * @example
3881
- * // returns false
3882
- * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 300 }))
3883
- * @example
3884
- * // returns true
3885
- * Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 800 }))
3886
- * @example
3887
- * // returns true
3888
- * Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 500 }))
3889
- * @example
3890
- * // returns false
3891
- * Dinero({ amount: 800 }).lessThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
3892
- *
3893
- * @throws {TypeError} If `comparator` has a different currency.
3894
- *
3895
- * @return {Boolean}
3896
- */
3897
- lessThanOrEqual: function lessThanOrEqual(comparator) {
3898
- assertSameCurrency.call(this, comparator);
3899
- var comparators = Dinero.normalizePrecision([this, comparator]);
3900
- return comparators[0].getAmount() <= comparators[1].getAmount();
3901
- },
3902
-
3903
- /**
3904
- * Checks whether the value represented by this object is greater than the other.
3905
- *
3906
- * @param {Dinero} comparator - The Dinero object to compare to.
3907
- *
3908
- * @example
3909
- * // returns false
3910
- * Dinero({ amount: 500 }).greaterThan(Dinero({ amount: 800 }))
3911
- * @example
3912
- * // returns true
3913
- * Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 500 }))
3914
- * @example
3915
- * // returns true
3916
- * Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 5000, precision: 3 }))
3917
- * @example
3918
- * // returns false
3919
- * Dinero({ amount: 5000, precision: 3 }).greaterThan(Dinero({ amount: 800 }))
3920
- *
3921
- * @throws {TypeError} If `comparator` has a different currency.
3922
- *
3923
- * @return {Boolean}
3924
- */
3925
- greaterThan: function greaterThan(comparator) {
3926
- assertSameCurrency.call(this, comparator);
3927
- var comparators = Dinero.normalizePrecision([this, comparator]);
3928
- return comparators[0].getAmount() > comparators[1].getAmount();
3929
- },
3930
-
3931
- /**
3932
- * Checks whether the value represented by this object is greater than or equal to the other.
3933
- *
3934
- * @param {Dinero} comparator - The Dinero object to compare to.
3935
- *
3936
- * @example
3937
- * // returns true
3938
- * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 300 }))
3939
- * @example
3940
- * // returns true
3941
- * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 500 }))
3942
- * @example
3943
- * // returns false
3944
- * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 800 }))
3945
- * @example
3946
- * // returns true
3947
- * Dinero({ amount: 800 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
3948
- * @example
3949
- * // returns true
3950
- * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
3951
- * @example
3952
- * // returns false
3953
- * Dinero({ amount: 5000, precision: 3 }).greaterThanOrEqual(Dinero({ amount: 800 }))
3954
- *
3955
- * @throws {TypeError} If `comparator` has a different currency.
3956
- *
3957
- * @return {Boolean}
3958
- */
3959
- greaterThanOrEqual: function greaterThanOrEqual(comparator) {
3960
- assertSameCurrency.call(this, comparator);
3961
- var comparators = Dinero.normalizePrecision([this, comparator]);
3962
- return comparators[0].getAmount() >= comparators[1].getAmount();
3963
- },
3964
-
3965
- /**
3966
- * Checks if the value represented by this object is zero.
3967
- *
3968
- * @example
3969
- * // returns true
3970
- * Dinero({ amount: 0 }).isZero()
3971
- * @example
3972
- * // returns false
3973
- * Dinero({ amount: 100 }).isZero()
3974
- *
3975
- * @return {Boolean}
3976
- */
3977
- isZero: function isZero() {
3978
- return this.getAmount() === 0;
3979
- },
3980
-
3981
- /**
3982
- * Checks if the value represented by this object is positive.
3983
- *
3984
- * @example
3985
- * // returns false
3986
- * Dinero({ amount: -10 }).isPositive()
3987
- * @example
3988
- * // returns true
3989
- * Dinero({ amount: 10 }).isPositive()
3990
- * @example
3991
- * // returns true
3992
- * Dinero({ amount: 0 }).isPositive()
3993
- *
3994
- * @return {Boolean}
3995
- */
3996
- isPositive: function isPositive() {
3997
- return this.getAmount() >= 0;
3998
- },
3999
-
4000
- /**
4001
- * Checks if the value represented by this object is negative.
4002
- *
4003
- * @example
4004
- * // returns true
4005
- * Dinero({ amount: -10 }).isNegative()
4006
- * @example
4007
- * // returns false
4008
- * Dinero({ amount: 10 }).isNegative()
4009
- * @example
4010
- * // returns false
4011
- * Dinero({ amount: 0 }).isNegative()
4012
- *
4013
- * @return {Boolean}
4014
- */
4015
- isNegative: function isNegative() {
4016
- return this.getAmount() < 0;
4017
- },
4018
-
4019
- /**
4020
- * Checks if this has minor currency units.
4021
- * Deprecates {@link module:Dinero~hasCents hasCents}.
4022
- *
4023
- * @example
4024
- * // returns false
4025
- * Dinero({ amount: 1100 }).hasSubUnits()
4026
- * @example
4027
- * // returns true
4028
- * Dinero({ amount: 1150 }).hasSubUnits()
4029
- *
4030
- * @return {Boolean}
4031
- */
4032
- hasSubUnits: function hasSubUnits() {
4033
- return calculator$1.modulo(this.getAmount(), Math.pow(10, precision)) !== 0;
4034
- },
4035
-
4036
- /**
4037
- * Checks if this has minor currency units.
4038
- *
4039
- * @deprecated since version 1.4.0, will be removed in 2.0.0
4040
- * Use {@link module:Dinero~hasSubUnits hasSubUnits} instead.
4041
- *
4042
- * @example
4043
- * // returns false
4044
- * Dinero({ amount: 1100 }).hasCents()
4045
- * @example
4046
- * // returns true
4047
- * Dinero({ amount: 1150 }).hasCents()
4048
- *
4049
- * @return {Boolean}
4050
- */
4051
- hasCents: function hasCents() {
4052
- return calculator$1.modulo(this.getAmount(), Math.pow(10, precision)) !== 0;
4053
- },
4054
-
4055
- /**
4056
- * Checks whether the currency represented by this object equals to the other.
4057
- *
4058
- * @param {Dinero} comparator - The Dinero object to compare to.
4059
- *
4060
- * @example
4061
- * // returns true
4062
- * Dinero({ amount: 2000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'EUR' }))
4063
- * @example
4064
- * // returns false
4065
- * Dinero({ amount: 1000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'USD' }))
4066
- *
4067
- * @return {Boolean}
4068
- */
4069
- hasSameCurrency: function hasSameCurrency(comparator) {
4070
- return this.getCurrency() === comparator.getCurrency();
4071
- },
4072
-
4073
- /**
4074
- * Checks whether the amount represented by this object equals to the other.
4075
- *
4076
- * @param {Dinero} comparator - The Dinero object to compare to.
4077
- *
4078
- * @example
4079
- * // returns true
4080
- * Dinero({ amount: 1000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000 }))
4081
- * @example
4082
- * // returns false
4083
- * Dinero({ amount: 2000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000, currency: 'EUR' }))
4084
- * @example
4085
- * // returns true
4086
- * Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
4087
- * @example
4088
- * // returns false
4089
- * Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
4090
- *
4091
- * @return {Boolean}
4092
- */
4093
- hasSameAmount: function hasSameAmount(comparator) {
4094
- var comparators = Dinero.normalizePrecision([this, comparator]);
4095
- return comparators[0].getAmount() === comparators[1].getAmount();
4096
- },
4097
-
4098
- /**
4099
- * Returns this object formatted as a string.
4100
- *
4101
- * The format is a mask which defines how the output string will be formatted.
4102
- * It defines whether to display a currency, in what format, how many fraction digits to display and whether to use grouping separators.
4103
- * The output is formatted according to the applying locale.
4104
- *
4105
- * Object | Format | String
4106
- * :--------------------------- | :---------------- | :---
4107
- * `Dinero({ amount: 500050 })` | `'$0,0.00'` | $5,000.50
4108
- * `Dinero({ amount: 500050 })` | `'$0,0'` | $5,001
4109
- * `Dinero({ amount: 500050 })` | `'$0'` | $5001
4110
- * `Dinero({ amount: 500050 })` | `'$0.0'` | $5000.5
4111
- * `Dinero({ amount: 500050 })` | `'USD0,0.0'` | USD5,000.5
4112
- * `Dinero({ amount: 500050 })` | `'0,0.0 dollar'` | 5,000.5 dollars
4113
- *
4114
- * Don't try to substitute the `$` sign or the `USD` code with your target currency, nor adapt the format string to the exact format you want.
4115
- * The format is a mask which defines a pattern and returns a valid, localized currency string.
4116
- * If you want to display the object in a custom way, either use {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~toUnit toUnit} or {@link module:Dinero~toRoundedUnit toRoundedUnit} and manipulate the output string as you wish.
4117
- *
4118
- * {@link module:Dinero~toFormat toFormat} wraps around `Number.prototype.toLocaleString`. For that reason, **format will vary depending on how it's implemented in the end user's environment**.
4119
- *
4120
- * You can also use `toLocaleString` directly:
4121
- * `Dinero().toRoundedUnit(digits, roundingMode).toLocaleString(locale, options)`.
4122
- *
4123
- * By default, amounts are rounded using the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
4124
- * You can also specify a different `roundingMode` to better fit your needs.
4125
- *
4126
- * @param {String} [format='$0,0.00'] - The format mask to format to.
4127
- * @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
4128
- *
4129
- * @example
4130
- * // returns $2,000
4131
- * Dinero({ amount: 200000 }).toFormat('$0,0')
4132
- * @example
4133
- * // returns €50.5
4134
- * Dinero({ amount: 5050, currency: 'EUR' }).toFormat('$0,0.0')
4135
- * @example
4136
- * // returns 100 euros
4137
- * Dinero({ amount: 10000, currency: 'EUR' }).setLocale('fr-FR').toFormat('0,0 dollar')
4138
- * @example
4139
- * // returns 2000
4140
- * Dinero({ amount: 200000, currency: 'EUR' }).toFormat()
4141
- * @example
4142
- * // returns $10
4143
- * Dinero({ amount: 1050 }).toFormat('$0', 'HALF_EVEN')
4144
- *
4145
- * @return {String}
4146
- */
4147
- toFormat: function toFormat() {
4148
- var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : globalFormat;
4149
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
4150
- var formatter = Format(format);
4151
- return this.toRoundedUnit(formatter.getMinimumFractionDigits(), roundingMode).toLocaleString(this.getLocale(), {
4152
- currencyDisplay: formatter.getCurrencyDisplay(),
4153
- useGrouping: formatter.getUseGrouping(),
4154
- minimumFractionDigits: formatter.getMinimumFractionDigits(),
4155
- style: formatter.getStyle(),
4156
- currency: this.getCurrency()
4157
- });
4158
- },
4159
-
4160
- /**
4161
- * Returns the amount represented by this object in units.
4162
- *
4163
- * @example
4164
- * // returns 10.5
4165
- * Dinero({ amount: 1050 }).toUnit()
4166
- * @example
4167
- * // returns 10.545
4168
- * Dinero({ amount: 10545, precision: 3 }).toUnit()
4169
- *
4170
- * @return {Number}
4171
- */
4172
- toUnit: function toUnit() {
4173
- return calculator$1.divide(this.getAmount(), Math.pow(10, precision));
4174
- },
4175
-
4176
- /**
4177
- * Returns the amount represented by this object in rounded units.
4178
- *
4179
- * By default, the method uses the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
4180
- * You can also specify a different `roundingMode` to better fit your needs.
4181
- *
4182
- * @example
4183
- * // returns 10.6
4184
- * Dinero({ amount: 1055 }).toRoundedUnit(1)
4185
- * @example
4186
- * // returns 10
4187
- * Dinero({ amount: 1050 }).toRoundedUnit(0, 'HALF_EVEN')
4188
- *
4189
- * @param {Number} digits - The number of fraction digits to round to.
4190
- * @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
4191
- *
4192
- * @return {Number}
4193
- */
4194
- toRoundedUnit: function toRoundedUnit(digits) {
4195
- var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
4196
- var factor = Math.pow(10, digits);
4197
- return calculator$1.divide(calculator$1.round(calculator$1.multiply(this.toUnit(), factor), roundingMode), factor);
4198
- },
4199
-
4200
- /**
4201
- * Returns the object's data as an object literal.
4202
- *
4203
- * @example
4204
- * // returns { amount: 500, currency: 'EUR', precision: 2 }
4205
- * Dinero({ amount: 500, currency: 'EUR', precision: 2 }).toObject()
4206
- *
4207
- * @return {Object}
4208
- */
4209
- toObject: function toObject() {
4210
- return {
4211
- amount: amount,
4212
- currency: currency,
4213
- precision: precision
4214
- };
4215
- },
4216
-
4217
- /**
4218
- * Returns the object's data as an object literal.
4219
- *
4220
- * Alias of {@link module:Dinero~toObject toObject}.
4221
- * It is defined so that calling `JSON.stringify` on a Dinero object will automatically extract the relevant data.
4222
- *
4223
- * @example
4224
- * // returns '{"amount":500,"currency":"EUR","precision":2}'
4225
- * JSON.stringify(Dinero({ amount: 500, currency: 'EUR', precision: 2 }))
4226
- *
4227
- * @return {Object}
4228
- */
4229
- toJSON: function toJSON() {
4230
- return this.toObject();
4231
- }
4232
- };
4233
- };
4234
-
4235
- var dinero = Object.assign(Dinero, Defaults, Globals, Static);
4236
-
4237
- function formatCurrency(amount, withSymbol = true) {
4238
- if (!amount)
4239
- amount = 0;
4240
- function format(amount) {
4241
- const formattedString = withSymbol ? '$0,0.00' : '0,0.00';
4242
- return dinero({ amount: amount, currency: 'USD' }).toFormat(formattedString);
4243
- }
4244
- return (amount < 0) ? `(${format(-amount)})` : format(amount);
4245
- }
4246
- function formatDate(dateString) {
4247
- if (!dateString)
4248
- return '';
4249
- const date = new Date(dateString);
4250
- return format(date, 'MMM d, yyyy');
4251
- }
4252
- function formatTime(dateString) {
4253
- if (!dateString)
4254
- return '';
4255
- const date = new Date(dateString);
4256
- return format(date, 'h:mmaaa');
4257
- }
4258
-
4259
- const paymentsListCss = ":host{display:block}";
4260
-
4261
- const PaymentsList = class {
4262
- constructor(hostRef) {
4263
- registerInstance(this, hostRef);
4264
- this.accountId = undefined;
4265
- this.auth = {};
4266
- this.payments = [];
4267
- }
4268
- requestPropsChanged() {
4269
- this.fetchData();
4270
- }
4271
- fetchData() {
4272
- const accountId = this.accountId;
4273
- const endpoint = `account/${accountId}/payments`;
4274
- Api(this.auth.token).get(endpoint)
4275
- .then((response) => {
4276
- const data = response.data.map((dataItem) => new Payment(dataItem));
4277
- this.payments = data;
4278
- });
4279
- }
4280
- ;
4281
- render() {
4282
- return (h(Host, null, h("table", { class: "justifi-table" }, h("thead", null, h("tr", null, h("th", { scope: "col", title: "The date and time each payment was made" }, "Made on"), h("th", { scope: "col", title: "The dollar amount of each payment" }, "Amount"), h("th", { scope: "col" }, "Account"), h("th", { scope: "col" }, "Description"), h("th", { scope: "col" }, "Payment ID"), h("th", { scope: "col" }, "Cardholder"), h("th", { scope: "col" }, "Payment Method"), h("th", { scope: "col" }, "Status"))), h("tbody", null, this.payments.map((payment) => {
4283
- var _a, _b, _c, _d;
4284
- h("tr", null, h("td", null, h("div", null, formatDate(payment.created_at)), h("div", null, formatTime(payment.created_at))), h("td", null, formatCurrency(payment.amount)), h("td", null, payment.account_id), h("td", null, payment.description), h("td", null, payment.id), h("td", null, (_b = (_a = payment.payment_method) === null || _a === void 0 ? void 0 : _a.card) === null || _b === void 0 ? void 0 : _b.name), h("td", null, (_d = (_c = payment.payment_method) === null || _c === void 0 ? void 0 : _c.card) === null || _d === void 0 ? void 0 : _d.acct_last_four), h("td", null, payment.status));
4285
- })))));
4286
- }
4287
- static get watchers() { return {
4288
- "accountId": ["requestPropsChanged"],
4289
- "auth": ["requestPropsChanged"]
4290
- }; }
4291
- };
4292
- PaymentsList.style = paymentsListCss;
4293
-
4294
- export { BankAccountForm as B, CardForm as C, PaymentsList as P };