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