-
Notifications
You must be signed in to change notification settings - Fork 0
/
Duration.ts
480 lines (446 loc) · 11 KB
/
Duration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
const SECONDS_IN_DAY = 24 * 60 * 60
/**
* Represents an ISO 8601 duration.
*
* Here we add a day.
*
* ```js
* import { Duration } from '@jetblack/date'
*
* const duration = new Duration('P1D')
* const d1 = addDuration(new Date('2000-01-01T00:00:00Z'), duration)
* console.log(d1)
* // Sun Jan 02 2000 00:00:00 GMT+0000 (Greenwich Mean Time)
* ```
*
* Note that durations may be negative.
*
* ```js
* import { Duration } from '@jetblack/date'
*
* const duration = new Duration('-P1D')
* const d1 = addDuration(new Date('2000-01-01T00:00:00Z'), duration)
* console.log(d1)
* // Fri Dec 31 1999 00:00:00 GMT+0000 (Greenwich Mean Time)
* ```
* @category Duration
*/
export class Duration {
/** @ignore */
static readonly #DURATION_PATTERN =
/^(?<sign>-?[+-])?P((?<years>-?[+-]?\d+([.]\d+)?)Y)?((?<months>-?[+-]?\d+([.]\d+)?)M)?((?<weeks>-?[+-]?\d+([.]\d+)?)W)?((?<days>-?[+-]?\d+([.]\d+)?)D)?(T((?<hours>-?[+-]?\d+([.]\d+)?)H)?((?<minutes>-?[+-]?\d+([.]\d+)?)M)?((?<seconds>-?[+-]?\d+([.]\d+)?)S)?)?$/
/** @ignore */
static readonly #ZERO_STRING = 'PT0S'
/** @ignore */
#years: number
/** @ignore */
#months: number
/** @ignore */
#weeks: number
/** @ignore */
#days: number
/** @ignore */
#hours: number
/** @ignore */
#minutes: number
/** @ignore */
#seconds: number
/**
* Constructs a duration.
*
* The resulting duration will be simplified. For example 12 months will
* become 1 year and 0 months.
*
* From component values.
*
* ```js
* const duration = new Duration(2, 14, 0, 0, 24)
* console.log(duration.toString())
* // P3Y2M1D
* ```
*
* From a string.
*
* ```js
* const duration = new Duration('P2Y14MT24H')
* console.log(duration.toString())
* // P3Y2M1D
* ```
*
* From a value.
*
* ```js
* const duration = new Duration(98582400)
* console.log(duration.toString())
* // P3Y2M1D
* ```
*
* @param years The years.
* @param months The months.
* @param weeks The weeks.
* @param days The days.
* @param hours The hours.
* @param minutes The minutes.
* @param seconds The seconds.
*/
constructor(
years: number,
months: number,
weeks?: number,
days?: number,
hours?: number,
minutes?: number,
seconds?: number
)
/**
* Constructs a year from the string representation, the number of seconds,
* or another duration object.
*
* @param value The duration as a string, number, or duration.
*/
constructor(value: string | number | Duration)
constructor(...args: any[]) {
;[
this.#years,
this.#months,
this.#weeks,
this.#days,
this.#hours,
this.#minutes,
this.#seconds
] = Duration.#argsToValues(...args)
}
/** @ignore */
static #argsToValues(
...args: any[]
): [number, number, number, number, number, number, number] {
if (args.length == 0) {
return [0, 0, 0, 0, 0, 0, 0]
} else if (args.length === 1) {
const value = args[0]
if (typeof value === 'string') {
return Duration.#fromString(value)
} else if (typeof value === 'number') {
return Duration.#fromNumber(value)
} else if (value instanceof Duration) {
return [
value.#years,
value.#months,
value.#weeks,
value.#days,
value.#hours,
value.#minutes,
value.#seconds
]
} else {
return [NaN, NaN, NaN, NaN, NaN, NaN, NaN]
}
} else {
return Duration.#fromValues(
args[0],
args[1],
args[2],
args[3],
args[4],
args[5],
args[6]
)
}
}
/** @ignore */
#countSigns(): [number, number] {
let positiveCount = 0,
negativeCount = 0
const values = [
this.#years,
this.#months,
this.#weeks,
this.#days,
this.#hours,
this.#minutes,
this.#seconds
]
for (const value of values) {
if (value > 0) {
++positiveCount
} else if (value < 0) {
++negativeCount
}
}
return [positiveCount, negativeCount]
}
/**
* Creates a string representation of the duration.
*
* @returns An ISO 8601 duration.
*/
toString(): string {
const [positiveCount, negativeCount] = this.#countSigns()
if (positiveCount === 0 && negativeCount === 0) {
return Duration.#ZERO_STRING
}
const sign = negativeCount > positiveCount ? -1 : 1
let datePart = 'P'
if (this.#years !== 0) {
datePart += sign * this.#years + 'Y'
}
if (this.#months !== 0) {
datePart += sign * this.#months + 'M'
}
if (this.#weeks !== 0) {
datePart += sign * this.#weeks + 'W'
}
if (this.#days !== 0) {
datePart += sign * this.#days + 'D'
}
let timePart = 'T'
if (this.#hours !== 0) {
timePart += sign * this.#hours + 'H'
}
if (this.#minutes !== 0) {
timePart += sign * this.#minutes + 'M'
}
if (this.#seconds !== 0) {
timePart += sign * this.#seconds + 'S'
}
if (timePart !== 'T') {
datePart += timePart
}
if (sign === -1) {
datePart = '-' + datePart
}
return datePart
}
/**
* Gets the years.
*/
get years(): number {
return this.#years
}
/**
* Sets the years.
*/
set years(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#years = Math.trunc(value)
}
/**
* Gets the months.
*/
get months(): number {
return this.#months
}
/**
* Sets the months.
*
* If the value is greater than or equal to 12 the duration is simplified.
*/
set months(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#months = Math.trunc(value) % 12
this.years += Math.trunc(value / 12)
}
/**
* Gets the weeks.
*/
get weeks(): number {
return this.#weeks
}
/**
* Sets the weeks.
*/
set weeks(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#weeks = value
}
/**
* Gets the days.
*/
get days(): number {
return this.#days
}
/**
* Sets the days.
*
* If the value is greater than or equal to 7 the duration is simplified.
*/
set days(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#days = Math.trunc(value) % 7
this.weeks += Math.trunc(value / 7)
}
/**
* Gets the hours.
*/
get hours(): number {
return this.#hours
}
/**
* Sets the hours.
*
* If the value is greater than or equal to 24 the duration is simplified.
*/
set hours(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#hours = Math.trunc(value) % 24
this.days += Math.trunc(value / 24)
}
/**
* Gets the minutes.
*/
get minutes(): number {
return this.#minutes
}
/**
* Sets the minutes.
*
* If the value is greater than or equal to 60 the duration is simplified.
*/
set minutes(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#minutes = Math.trunc(value) % 60
this.hours += Math.trunc(value / 60)
}
/**
* Gets the seconds.
*/
get seconds(): number {
return this.#seconds
}
/**
* Sets the seconds.
*
* If the value is greater than or equal to 60 the value is simplified.
*/
set seconds(value: number) {
if (value < 0) {
throw new RangeError('Value cannot be negative')
}
this.#seconds = Math.trunc(value) % 60
this.minutes += Math.trunc(value / 60)
}
/**
* The number of milliseconds of the duration assuming a year has 360 days
* and a month has 30 days.
*
* Note that this is not idempotent. As the actual number of days in a year
* is not available, constant values are used. This means that 30 days is
* equivalent to a month.
*
* ```js
* const d1 = new Duration('P1M')
* console.log(d1.valueOf())
* // 2592000
*
* const d2 = new Duration('P30D')
* console.log(d1.valueOf())
* // 2592000
* ```
*
* @returns The number of milliseconds to which the duration corresponds.
*/
valueOf(): number {
const totalDays =
this.#years * 360 + this.#months * 30 + this.#weeks * 7 + this.#days
const totalSeconds =
this.#hours * 60 * 60 + this.#minutes * 60 + this.#seconds
return totalDays * SECONDS_IN_DAY + totalSeconds
}
/** @ignore */
static #fromString(
text: string
): [number, number, number, number, number, number, number] {
const match = Duration.#DURATION_PATTERN.exec(text)
if (match == null || match.groups == null) {
throw new Error('Failed to parse duration')
}
const sign = match.groups.sign === '-' ? -1 : 1
const years = sign * parseFloat(match.groups.years || '0'),
months = sign * parseFloat(match.groups.months || '0'),
weeks = sign * parseFloat(match.groups.weeks || '0'),
days = sign * parseFloat(match.groups.days || '0'),
hours = sign * parseFloat(match.groups.hours || '0'),
minutes = sign * parseFloat(match.groups.minutes || '0'),
seconds = sign * parseFloat(match.groups.seconds || '0')
return Duration.#fromValues(
years,
months,
weeks,
days,
hours,
minutes,
seconds
)
}
/** @ignore */
static #fromNumber(
value: number
): [number, number, number, number, number, number, number] {
let dateValue = Math.trunc(value / SECONDS_IN_DAY)
const years = Math.trunc(dateValue / 360)
dateValue = dateValue % 360
const months = Math.trunc(dateValue / 30)
dateValue = dateValue % 30
const days = dateValue
let timeValue = value % SECONDS_IN_DAY
const hours = Math.trunc(timeValue / 60 / 60)
timeValue = timeValue % (60 * 60)
const minutes = Math.trunc(timeValue / 60)
const seconds = timeValue % 60
return [
years,
months,
Math.trunc(days / 7),
days % 7,
hours,
minutes,
seconds
]
}
/** @ignore */
static #fromValues(
years: number,
months: number,
weeks: number = 0,
days: number = 0,
hours: number = 0,
minutes: number = 0,
seconds: number = 0
): [number, number, number, number, number, number, number] {
const totalMinutes = minutes + Math.trunc(seconds / 60)
const totalHours = hours + Math.trunc(totalMinutes / 60)
const totalDays = days + Math.trunc(totalHours / 24)
const totalMonths = years * 12 + months
return [
Math.trunc(totalMonths / 12),
totalMonths % 12,
weeks + Math.trunc(totalDays / 7),
totalDays % 7,
totalHours % 24,
totalMinutes % 60,
seconds % 60
]
}
[Symbol.toPrimitive](hint: string): any {
if (hint === 'string') {
return this.toString()
} else if (hint === 'number') {
return this.valueOf()
} else {
// hint === 'default'
return this.toString()
}
}
}