@quenty/time 2.5.0 → 2.6.0

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.
@@ -0,0 +1,890 @@
1
+ --!strict
2
+ --[=[
3
+ Durations. A duration is a length of time with no
4
+ start point, kept as a number of seconds to match Roblox's `os.time`, `task.wait` and friends.
5
+ A year is counted as 365 days and a month as 30 days when converting to and from
6
+ seconds.
7
+
8
+ ```lua
9
+ TimeDurationUtils.format({ hours = 1, minutes = 30 }, "hh:mm") --> 01:30
10
+ TimeDurationUtils.humanize(TimeDurationUtils.toSeconds(2, "days")) --> 2 days
11
+ TimeDurationUtils.toIsoString("PT90M") --> PT1H30M
12
+ ```
13
+
14
+ @class TimeDurationUtils
15
+ ]=]
16
+
17
+ local require = require(script.Parent.loader).load(script)
18
+
19
+ local RelativeTimeUtils = require("RelativeTimeUtils")
20
+ local Time = require("Time")
21
+ local TimeLocalizationUtils = require("TimeLocalizationUtils")
22
+
23
+ local TimeDurationUtils = {}
24
+
25
+ --[=[
26
+ Units of a duration. Singular keys are accepted as well.
27
+
28
+ @interface DurationTable
29
+ .years number?
30
+ .months number?
31
+ .weeks number?
32
+ .days number?
33
+ .hours number?
34
+ .minutes number?
35
+ .seconds number?
36
+ .milliseconds number?
37
+ @within TimeDurationUtils
38
+ ]=]
39
+ export type DurationTable = {
40
+ years: number?,
41
+ months: number?,
42
+ weeks: number?,
43
+ days: number?,
44
+ hours: number?,
45
+ minutes: number?,
46
+ seconds: number?,
47
+ milliseconds: number?,
48
+ }
49
+
50
+ --[=[
51
+ A number of seconds, a [DurationTable], or an ISO 8601 duration such as `"P1DT12H"`.
52
+
53
+ @type DurationLike number | DurationTable | string
54
+ @within TimeDurationUtils
55
+ ]=]
56
+ export type DurationLike = number | DurationTable | string
57
+
58
+ --[=[
59
+ A duration broken into whole units, largest first, as [TimeDurationUtils.toTable] returns it.
60
+
61
+ @interface DurationBreakdown
62
+ .years number
63
+ .months number
64
+ .days number
65
+ .hours number
66
+ .minutes number
67
+ .seconds number
68
+ .milliseconds number
69
+ @within TimeDurationUtils
70
+ ]=]
71
+ export type DurationBreakdown = {
72
+ years: number,
73
+ months: number,
74
+ days: number,
75
+ hours: number,
76
+ minutes: number,
77
+ seconds: number,
78
+ milliseconds: number,
79
+ }
80
+
81
+ --[=[
82
+ See [TimeLocalizationUtils.DurationStringOverrides].
83
+
84
+ @type DurationStringOverrides TimeLocalizationUtils.DurationStringOverrides
85
+ @within TimeDurationUtils
86
+ ]=]
87
+ export type DurationStringOverrides = TimeLocalizationUtils.DurationStringOverrides
88
+
89
+ --[=[
90
+ Which zero-valued tokens [TimeDurationUtils.format] drops: `large` the leading ones, `small`
91
+ the trailing ones, `mid` the interior ones, `both` leading and trailing, `all` every one and
92
+ `false` none. The last remaining token is never dropped.
93
+
94
+ @type DurationTrim "large" | "small" | "both" | "mid" | "all" | false
95
+ @within TimeDurationUtils
96
+ ]=]
97
+ export type DurationTrim = "large" | "small" | "both" | "mid" | "all" | false
98
+
99
+ --[=[
100
+ Options for [TimeDurationUtils.format].
101
+
102
+ @interface DurationFormatOptions
103
+ .locale string? -- Picks the unit phrases through [TimeLocalizationUtils], defaults to English
104
+ .strings DurationStringOverrides? -- Overrides the phrase for a unit, e.g. `{ hours = { one = "%d hr", other = "%d hrs" } }`
105
+ .trim DurationTrim? -- Which zero tokens to drop, defaults to `large`
106
+ .stopTrim string? -- Tokens never dropped, as a template such as `m`; `*` before a token in the template does the same
107
+ .largest number? -- Show only this many of the largest non-zero tokens; implies `trim = "all"` unless `trim` is given
108
+ .trunc boolean? -- Truncate the smallest token instead of rounding it
109
+ .precision number? -- Decimal places on the smallest token; negative rounds to tens, hundreds and so on
110
+ .forceLength boolean? -- Pad the first shown token to its template width even when a larger one was dropped
111
+ .minValue number? -- Below this many of the smallest unit, print `< ` and the minimum instead
112
+ .maxValue number? -- Above this many of the smallest unit, print `> ` and the maximum instead
113
+ .limits { [string]: number }? -- How far a token may count before the next larger token is used: `{ minutes = 60 }` prints one hour as `60:00`, `{ hours = 47 }` prints a day and a half as `36:00:00`
114
+ @within TimeDurationUtils
115
+ ]=]
116
+ export type DurationFormatOptions = {
117
+ locale: string?,
118
+ strings: DurationStringOverrides?,
119
+ trim: DurationTrim?,
120
+ stopTrim: string?,
121
+ largest: number?,
122
+ trunc: boolean?,
123
+ precision: number?,
124
+ forceLength: boolean?,
125
+ minValue: number?,
126
+ maxValue: number?,
127
+ limits: { [string]: number }?,
128
+ }
129
+
130
+ local SECONDS_A_MINUTE = 60
131
+ local SECONDS_AN_HOUR = 60 * SECONDS_A_MINUTE
132
+ local SECONDS_A_DAY = 24 * SECONDS_AN_HOUR
133
+ local SECONDS_A_WEEK = 7 * SECONDS_A_DAY
134
+ local SECONDS_A_MONTH = 30 * SECONDS_A_DAY
135
+ local SECONDS_A_YEAR = 365 * SECONDS_A_DAY
136
+
137
+ local UNIT_SECONDS: { [string]: number } = {
138
+ millisecond = 0.001,
139
+ second = 1,
140
+ minute = SECONDS_A_MINUTE,
141
+ hour = SECONDS_AN_HOUR,
142
+ day = SECONDS_A_DAY,
143
+ week = SECONDS_A_WEEK,
144
+ month = SECONDS_A_MONTH,
145
+ quarter = 3 * SECONDS_A_MONTH,
146
+ year = SECONDS_A_YEAR,
147
+ }
148
+
149
+ -- Breakdown field for each unit that has one
150
+ local UNIT_BREAKDOWN_FIELD: { [string]: string } = {
151
+ millisecond = "milliseconds",
152
+ second = "seconds",
153
+ minute = "minutes",
154
+ hour = "hours",
155
+ day = "days",
156
+ week = "weeks",
157
+ month = "months",
158
+ year = "years",
159
+ }
160
+
161
+ -- ISO 8601 designators before and after the T
162
+ local ISO_DATE_UNITS: { [string]: number } = {
163
+ Y = SECONDS_A_YEAR,
164
+ M = SECONDS_A_MONTH,
165
+ W = SECONDS_A_WEEK,
166
+ D = SECONDS_A_DAY,
167
+ }
168
+ local ISO_TIME_UNITS: { [string]: number } = {
169
+ H = SECONDS_AN_HOUR,
170
+ M = SECONDS_A_MINUTE,
171
+ S = 1,
172
+ }
173
+
174
+ type FormatToken = {
175
+ letter: string,
176
+ field: Time.TimeUnit?,
177
+ milliseconds: number,
178
+ }
179
+
180
+ function TimeDurationUtils._formatToken(letter: string, field: Time.TimeUnit?, milliseconds: number): FormatToken
181
+ return { letter = letter, field = field, milliseconds = milliseconds }
182
+ end
183
+
184
+ -- Template letters, largest first, with each unit's size in milliseconds
185
+ local FORMAT_TOKENS: { FormatToken } = {
186
+ TimeDurationUtils._formatToken("y", "years", SECONDS_A_YEAR * 1000),
187
+ TimeDurationUtils._formatToken("M", "months", SECONDS_A_MONTH * 1000),
188
+ TimeDurationUtils._formatToken("w", "weeks", SECONDS_A_WEEK * 1000),
189
+ TimeDurationUtils._formatToken("d", "days", SECONDS_A_DAY * 1000),
190
+ TimeDurationUtils._formatToken("h", "hours", SECONDS_AN_HOUR * 1000),
191
+ TimeDurationUtils._formatToken("m", "minutes", SECONDS_A_MINUTE * 1000),
192
+ TimeDurationUtils._formatToken("s", "seconds", 1000),
193
+ -- Centiseconds have no TimeUnit, so they take no limit and no `__` phrase
194
+ TimeDurationUtils._formatToken("C", nil, 10),
195
+ TimeDurationUtils._formatToken("S", "milliseconds", 1),
196
+ }
197
+
198
+ local FORMAT_TOKEN_RANK: { [string]: number } = {}
199
+ for rank, token in FORMAT_TOKENS do
200
+ FORMAT_TOKEN_RANK[token.letter] = rank
201
+ end
202
+
203
+ -- One piece of a parsed template: literal text, or a unit token with its padding width
204
+ type FormatPart = {
205
+ text: string?,
206
+ rank: number?,
207
+ width: number?,
208
+ label: boolean?,
209
+ stop: boolean?,
210
+ hidden: boolean?,
211
+ value: number?,
212
+ }
213
+
214
+ function TimeDurationUtils._unitSeconds(unit: Time.TimeUnit): number
215
+ return UNIT_SECONDS[Time._normalizeUnit(unit)]
216
+ end
217
+
218
+ -- Truncates toward zero, so a negative duration breaks into negative parts
219
+ function TimeDurationUtils._truncate(value: number): number
220
+ return if value < 0 then math.ceil(value) else math.floor(value)
221
+ end
222
+
223
+ function TimeDurationUtils._parseIsoPart(part: string, units: { [string]: number }, source: string): number
224
+ local total = 0
225
+ local index = 1
226
+
227
+ while index <= #part do
228
+ local numberText, letter, nextIndex = string.match(part, "^([-+]?[%d.,]*)(%a)()", index)
229
+ assert(letter and units[letter], string.format("Bad ISO 8601 duration %q", source))
230
+
231
+ local value = tonumber((string.gsub(numberText :: string, ",", "."))) or 0
232
+ total += value * units[letter]
233
+ index = nextIndex :: any
234
+ end
235
+
236
+ return total
237
+ end
238
+
239
+ function TimeDurationUtils._parseIso(iso: string): number
240
+ local sign, body = string.match(iso, "^([-+]?)P(.*)$")
241
+ assert(body, string.format("Bad ISO 8601 duration %q", iso))
242
+
243
+ local datePart, timePart = string.match(body :: string, "^([^T]*)T(.*)$")
244
+ if not datePart then
245
+ datePart = body
246
+ timePart = ""
247
+ end
248
+
249
+ local total = TimeDurationUtils._parseIsoPart(datePart :: string, ISO_DATE_UNITS, iso)
250
+ + TimeDurationUtils._parseIsoPart(timePart :: string, ISO_TIME_UNITS, iso)
251
+
252
+ return if sign == "-" then -total else total
253
+ end
254
+
255
+ --[=[
256
+ Normalizes any [DurationLike] to seconds. A bare number is seconds unless `unit` says
257
+ otherwise, so `toSeconds(5, "minutes")` is `300`.
258
+ ]=]
259
+ function TimeDurationUtils.toSeconds(duration: DurationLike, unit: Time.TimeUnit?): number
260
+ if type(duration) == "number" then
261
+ return if unit then duration * TimeDurationUtils._unitSeconds(unit) else duration
262
+ elseif type(duration) == "string" then
263
+ assert(unit == nil, "A unit cannot be given with an ISO 8601 duration")
264
+ return TimeDurationUtils._parseIso(duration)
265
+ elseif type(duration) == "table" then
266
+ assert(unit == nil, "A unit cannot be given with a duration table")
267
+
268
+ local total = 0
269
+ for key, value in pairs(duration :: any) do
270
+ assert(type(value) == "number", string.format("Bad value for %q", tostring(key)))
271
+ total += value * TimeDurationUtils._unitSeconds(key)
272
+ end
273
+
274
+ return total
275
+ else
276
+ error(string.format("Bad duration %q", typeof(duration)))
277
+ end
278
+ end
279
+
280
+ --[=[
281
+ Normalizes any [DurationLike] to milliseconds. See [TimeDurationUtils.toSeconds].
282
+ ]=]
283
+ function TimeDurationUtils.toMilliseconds(duration: DurationLike, unit: Time.TimeUnit?): number
284
+ return TimeDurationUtils.toSeconds(duration, unit) * 1000
285
+ end
286
+
287
+ --[=[
288
+ Returns the whole duration in one unit, fractional. `as(90, "minutes")`
289
+ is `1.5`.
290
+ ]=]
291
+ function TimeDurationUtils.as(duration: DurationLike, unit: Time.TimeUnit): number
292
+ return TimeDurationUtils.toSeconds(duration) / TimeDurationUtils._unitSeconds(unit)
293
+ end
294
+
295
+ --[=[
296
+ Breaks the duration into whole years, months, days, hours, minutes, seconds and milliseconds,
297
+ largest first.
298
+ ]=]
299
+ function TimeDurationUtils.toTable(duration: DurationLike): DurationBreakdown
300
+ local seconds = TimeDurationUtils.toSeconds(duration)
301
+ -- Work in whole milliseconds so fractional seconds do not leak float noise into the parts
302
+ local remaining = TimeDurationUtils._truncate(seconds * 1000 + (if seconds < 0 then -0.5 else 0.5))
303
+
304
+ local years = TimeDurationUtils._truncate(remaining / (SECONDS_A_YEAR * 1000))
305
+ remaining = math.fmod(remaining, SECONDS_A_YEAR * 1000)
306
+ local months = TimeDurationUtils._truncate(remaining / (SECONDS_A_MONTH * 1000))
307
+ remaining = math.fmod(remaining, SECONDS_A_MONTH * 1000)
308
+ local days = TimeDurationUtils._truncate(remaining / (SECONDS_A_DAY * 1000))
309
+ remaining = math.fmod(remaining, SECONDS_A_DAY * 1000)
310
+ local hours = TimeDurationUtils._truncate(remaining / (SECONDS_AN_HOUR * 1000))
311
+ remaining = math.fmod(remaining, SECONDS_AN_HOUR * 1000)
312
+ local minutes = TimeDurationUtils._truncate(remaining / (SECONDS_A_MINUTE * 1000))
313
+ remaining = math.fmod(remaining, SECONDS_A_MINUTE * 1000)
314
+ local wholeSeconds = TimeDurationUtils._truncate(remaining / 1000)
315
+ remaining = math.fmod(remaining, 1000)
316
+
317
+ return {
318
+ years = years,
319
+ months = months,
320
+ days = days,
321
+ hours = hours,
322
+ minutes = minutes,
323
+ seconds = wholeSeconds,
324
+ milliseconds = remaining,
325
+ }
326
+ end
327
+
328
+ --[=[
329
+ Returns one whole unit of the breakdown: `get({ hours = 25 }, "hours")` is
330
+ `1` and `get({ hours = 25 }, "days")` is `1`. Weeks are whole weeks within the days and
331
+ quarters whole quarters within the months.
332
+ ]=]
333
+ function TimeDurationUtils.get(duration: DurationLike, unit: Time.TimeUnit): number
334
+ local normalized = Time._normalizeUnit(unit)
335
+ local breakdown = TimeDurationUtils.toTable(duration)
336
+
337
+ if normalized == "week" then
338
+ return TimeDurationUtils._truncate(breakdown.days / 7)
339
+ elseif normalized == "quarter" then
340
+ return TimeDurationUtils._truncate(breakdown.months / 3)
341
+ end
342
+
343
+ return (breakdown :: any)[UNIT_BREAKDOWN_FIELD[normalized]]
344
+ end
345
+
346
+ --[=[
347
+ Adds another duration, returning seconds. `unit` applies when `other` is a number.
348
+ ]=]
349
+ function TimeDurationUtils.add(duration: DurationLike, other: DurationLike, unit: Time.TimeUnit?): number
350
+ return TimeDurationUtils.toSeconds(duration) + TimeDurationUtils.toSeconds(other, unit)
351
+ end
352
+
353
+ --[=[
354
+ Subtracts another duration, returning seconds. `unit` applies when `other` is a number.
355
+ ]=]
356
+ function TimeDurationUtils.subtract(duration: DurationLike, other: DurationLike, unit: Time.TimeUnit?): number
357
+ return TimeDurationUtils.toSeconds(duration) - TimeDurationUtils.toSeconds(other, unit)
358
+ end
359
+
360
+ --[=[
361
+ Prints an amount with its unit, pluralized for the locale: `formatUnit("days", 1)` is
362
+ `1 day` and `formatUnit("days", 45)` is `45 days`. The amount is printed as given, so
363
+ `formatUnit("hours", 1.5)` is `1.5 hours`. Quarters have no phrase.
364
+
365
+ ```lua
366
+ TimeDurationUtils.formatUnit("hours", 2, { locale = "es-es" }) --> 2 horas
367
+ ```
368
+ ]=]
369
+ function TimeDurationUtils.formatUnit(unit: Time.TimeUnit, amount: number, options: DurationFormatOptions?): string
370
+ assert(type(amount) == "number", "Bad amount")
371
+
372
+ local field = UNIT_BREAKDOWN_FIELD[Time._normalizeUnit(unit)]
373
+ assert(field, string.format("No duration phrase for %q", tostring(unit)))
374
+
375
+ local overrides = if options then options.strings else nil
376
+ local localeStrings: any =
377
+ TimeLocalizationUtils.getDurationStringsForLocale(if options then options.locale else nil)
378
+ local phrase = (if overrides then overrides[field] else nil) or localeStrings[field]
379
+ assert(phrase, string.format("No duration phrase for %q", field))
380
+
381
+ if type(phrase) == "function" then
382
+ return phrase(amount)
383
+ end
384
+
385
+ local template = if math.abs(amount) == 1 then phrase.one else phrase.other
386
+ return (string.gsub(template, "%%d", tostring(amount)))
387
+ end
388
+
389
+ function TimeDurationUtils._appendText(parts: { FormatPart }, text: string)
390
+ local last = parts[#parts]
391
+ if last and last.text then
392
+ last.text ..= text
393
+ else
394
+ table.insert(parts, { text = text })
395
+ end
396
+ end
397
+
398
+ function TimeDurationUtils._tokenizeTemplate(template: string): { FormatPart }
399
+ local parts: { FormatPart } = {}
400
+ local index = 1
401
+ local stopNext = false
402
+
403
+ while index <= #template do
404
+ local char = string.sub(template, index, index)
405
+ local rank = FORMAT_TOKEN_RANK[char]
406
+
407
+ if char == "[" then
408
+ local closeIndex = string.find(template, "]", index, true)
409
+ if closeIndex then
410
+ TimeDurationUtils._appendText(parts, string.sub(template, index + 1, closeIndex - 1))
411
+ index = closeIndex + 1
412
+ else
413
+ TimeDurationUtils._appendText(parts, char)
414
+ index += 1
415
+ end
416
+ elseif char == "*" then
417
+ stopNext = true
418
+ index += 1
419
+ elseif rank then
420
+ local width = 1
421
+ while string.sub(template, index + width, index + width) == char do
422
+ width += 1
423
+ end
424
+ index += width
425
+
426
+ local labelEnd = string.match(template, "^%s*__()", index)
427
+ table.insert(parts, { rank = rank, width = width, stop = stopNext, label = labelEnd ~= nil })
428
+ stopNext = false
429
+ if labelEnd then
430
+ index = labelEnd :: any
431
+ end
432
+ else
433
+ TimeDurationUtils._appendText(parts, char)
434
+ index += 1
435
+ end
436
+ end
437
+
438
+ return parts
439
+ end
440
+
441
+ -- Shown tokens, largest first
442
+ function TimeDurationUtils._getShownTokens(parts: { FormatPart }): { FormatPart }
443
+ local shown: { FormatPart } = {}
444
+ for _, part in parts do
445
+ if part.rank and not part.hidden then
446
+ table.insert(shown, part)
447
+ end
448
+ end
449
+
450
+ table.sort(shown, function(a, b)
451
+ return (a.rank :: number) < (b.rank :: number)
452
+ end)
453
+
454
+ return shown
455
+ end
456
+
457
+ -- The largest shown token absorbs everything above it, the smallest is rounded or truncated
458
+ -- to the precision, and the rest hold the remainder in between
459
+ function TimeDurationUtils._assignValues(
460
+ parts: { FormatPart },
461
+ totalMilliseconds: number,
462
+ options: DurationFormatOptions
463
+ )
464
+ local shown = TimeDurationUtils._getShownTokens(parts)
465
+ local ranks: { number } = {}
466
+ for _, part in shown do
467
+ if ranks[#ranks] ~= part.rank then
468
+ table.insert(ranks, part.rank :: number)
469
+ end
470
+ end
471
+
472
+ local precision = options.precision or 0
473
+ local unitsPerStep = 10 ^ precision
474
+ local smallestMilliseconds = FORMAT_TOKENS[ranks[#ranks]].milliseconds
475
+
476
+ local steps = totalMilliseconds / smallestMilliseconds * unitsPerStep
477
+ steps = if options.trunc then math.floor(steps + 1e-9) else math.floor(steps + 0.5)
478
+
479
+ local values: { [number]: number } = {}
480
+ for i = 1, #ranks - 1 do
481
+ local ratio = FORMAT_TOKENS[ranks[i]].milliseconds / smallestMilliseconds * unitsPerStep
482
+ local value = math.floor(steps / ratio + 1e-9)
483
+ steps -= value * ratio
484
+ values[ranks[i]] = value
485
+ end
486
+ values[ranks[#ranks]] = steps / unitsPerStep
487
+
488
+ for _, part in shown do
489
+ part.value = values[part.rank :: number]
490
+ end
491
+ end
492
+
493
+ function TimeDurationUtils._getStopRanks(options: DurationFormatOptions): { [number]: boolean }
494
+ local stopRanks: { [number]: boolean } = {}
495
+ if options.stopTrim then
496
+ for _, part in TimeDurationUtils._tokenizeTemplate(options.stopTrim) do
497
+ if part.rank then
498
+ stopRanks[part.rank] = true
499
+ end
500
+ end
501
+ end
502
+
503
+ return stopRanks
504
+ end
505
+
506
+ function TimeDurationUtils._isPinned(part: FormatPart, stopRanks: { [number]: boolean }): boolean
507
+ return part.stop == true or stopRanks[part.rank :: number] == true
508
+ end
509
+
510
+ function TimeDurationUtils._canHide(part: FormatPart, stopRanks: { [number]: boolean }): boolean
511
+ return part.value == 0 and not TimeDurationUtils._isPinned(part, stopRanks)
512
+ end
513
+
514
+ -- Hides the largest shown token while the next smaller token can still count the whole
515
+ -- duration within its limit, so `{ minutes = 60 }` prints one hour as `60:00`
516
+ function TimeDurationUtils._applyLimits(
517
+ parts: { FormatPart },
518
+ totalMilliseconds: number,
519
+ options: DurationFormatOptions
520
+ )
521
+ local limits: { [string]: number } = {}
522
+ for unit, limit in pairs(options.limits or {}) do
523
+ limits[Time._normalizeUnit(unit :: any)] = limit
524
+ end
525
+
526
+ local stopRanks = TimeDurationUtils._getStopRanks(options)
527
+
528
+ while true do
529
+ local shown = TimeDurationUtils._getShownTokens(parts)
530
+ local largest = shown[1]
531
+ local largestRank = largest.rank :: number
532
+
533
+ local next
534
+ for _, part in shown do
535
+ if part.rank ~= largestRank then
536
+ next = part
537
+ break
538
+ end
539
+ end
540
+ if next == nil or TimeDurationUtils._isPinned(largest, stopRanks) then
541
+ return
542
+ end
543
+
544
+ local nextField: Time.TimeUnit? = FORMAT_TOKENS[next.rank :: number].field
545
+ local limit = if nextField then limits[Time._normalizeUnit(nextField)] else nil
546
+ if limit == nil then
547
+ return
548
+ end
549
+
550
+ for _, part in shown do
551
+ if part.rank == largestRank then
552
+ part.hidden = true
553
+ end
554
+ end
555
+ TimeDurationUtils._assignValues(parts, totalMilliseconds, options)
556
+
557
+ if (next.value :: number) > limit then
558
+ for _, part in shown do
559
+ if part.rank == largestRank then
560
+ part.hidden = false
561
+ end
562
+ end
563
+ TimeDurationUtils._assignValues(parts, totalMilliseconds, options)
564
+ return
565
+ end
566
+ end
567
+ end
568
+
569
+ function TimeDurationUtils._trimParts(parts: { FormatPart }, options: DurationFormatOptions)
570
+ local tokens: { FormatPart } = {}
571
+ for _, part in parts do
572
+ if part.rank then
573
+ table.insert(tokens, part)
574
+ end
575
+ end
576
+
577
+ local stopRanks = TimeDurationUtils._getStopRanks(options)
578
+
579
+ local mode: any = options.trim
580
+ if mode == nil then
581
+ mode = if options.largest then "all" else "large" :: DurationTrim
582
+ end
583
+
584
+ if options.largest then
585
+ local kept = 0
586
+ for _, part in TimeDurationUtils._getShownTokens(parts) do
587
+ if part.value ~= 0 and kept < options.largest then
588
+ kept += 1
589
+ elseif not TimeDurationUtils._isPinned(part, stopRanks) then
590
+ part.hidden = true
591
+ end
592
+ end
593
+ end
594
+
595
+ if mode == "large" or mode == "both" or mode == "all" then
596
+ for _, part in tokens do
597
+ if part.hidden then
598
+ continue
599
+ elseif TimeDurationUtils._canHide(part, stopRanks) then
600
+ part.hidden = true
601
+ else
602
+ break
603
+ end
604
+ end
605
+ end
606
+
607
+ if mode == "small" or mode == "both" or mode == "all" then
608
+ for i = #tokens, 1, -1 do
609
+ local part = tokens[i]
610
+ if part.hidden then
611
+ continue
612
+ elseif TimeDurationUtils._canHide(part, stopRanks) then
613
+ part.hidden = true
614
+ else
615
+ break
616
+ end
617
+ end
618
+ end
619
+
620
+ if mode == "mid" or mode == "all" then
621
+ local firstShown, lastShown
622
+ for i, part in tokens do
623
+ if not part.hidden then
624
+ firstShown = firstShown or i
625
+ lastShown = i
626
+ end
627
+ end
628
+
629
+ if firstShown and lastShown then
630
+ for i = firstShown + 1, lastShown - 1 do
631
+ if TimeDurationUtils._canHide(tokens[i], stopRanks) then
632
+ tokens[i].hidden = true
633
+ end
634
+ end
635
+ end
636
+ end
637
+
638
+ local anyShown = false
639
+ for _, part in tokens do
640
+ anyShown = anyShown or not part.hidden
641
+ end
642
+ if not anyShown and #tokens > 0 then
643
+ tokens[#tokens].hidden = false
644
+ end
645
+ end
646
+
647
+ function TimeDurationUtils._formatTokenValue(
648
+ part: FormatPart,
649
+ padded: boolean,
650
+ isSmallest: boolean,
651
+ options: DurationFormatOptions
652
+ ): string
653
+ local value = part.value :: number
654
+ local precision = options.precision or 0
655
+ local hasDecimals = isSmallest and precision > 0
656
+ local text = if hasDecimals
657
+ then string.format("%." .. precision .. "f", value)
658
+ else tostring(math.floor(value + 0.5))
659
+
660
+ if part.label then
661
+ local field: Time.TimeUnit? = FORMAT_TOKENS[part.rank :: number].field
662
+ assert(field, string.format("No duration phrase for %q", FORMAT_TOKENS[part.rank :: number].letter))
663
+ return TimeDurationUtils.formatUnit(field, tonumber(text) :: number, options)
664
+ end
665
+
666
+ local width = part.width :: number
667
+ local integerLength = #(string.match(text, "^%d+") :: string)
668
+ if padded and integerLength < width then
669
+ text = string.rep("0", width - integerLength) .. text
670
+ end
671
+
672
+ return text
673
+ end
674
+
675
+ -- A gap between tokens is dropped when the token before it was hidden, or when the token after
676
+ -- it starts a hidden run that reaches the end of the template
677
+ function TimeDurationUtils._isGapDropped(parts: { FormatPart }, index: number): boolean
678
+ local previous, next
679
+ for j = index - 1, 1, -1 do
680
+ if parts[j].rank then
681
+ previous = parts[j]
682
+ break
683
+ end
684
+ end
685
+ for j = index + 1, #parts do
686
+ if parts[j].rank then
687
+ next = parts[j]
688
+ break
689
+ end
690
+ end
691
+
692
+ if not previous or not next then
693
+ return false
694
+ elseif previous.hidden then
695
+ return true
696
+ elseif not next.hidden then
697
+ return false
698
+ end
699
+
700
+ for j = index + 1, #parts do
701
+ if parts[j].rank and not parts[j].hidden then
702
+ return false
703
+ end
704
+ end
705
+
706
+ return true
707
+ end
708
+
709
+ function TimeDurationUtils._renderParts(
710
+ parts: { FormatPart },
711
+ isNegative: boolean,
712
+ options: DurationFormatOptions
713
+ ): string
714
+ local shown = TimeDurationUtils._getShownTokens(parts)
715
+ local smallestRank = shown[#shown].rank
716
+
717
+ local firstTokenIndex, firstShownIndex
718
+ for i, part in parts do
719
+ if part.rank then
720
+ firstTokenIndex = firstTokenIndex or i
721
+ if not part.hidden then
722
+ firstShownIndex = firstShownIndex or i
723
+ end
724
+ end
725
+ end
726
+
727
+ local pieces: { string } = {}
728
+ for i, part in parts do
729
+ if part.text then
730
+ if not TimeDurationUtils._isGapDropped(parts, i) then
731
+ table.insert(pieces, part.text)
732
+ end
733
+ elseif not part.hidden then
734
+ local padded = i == firstTokenIndex or i ~= firstShownIndex or options.forceLength == true
735
+ if i == firstShownIndex and isNegative then
736
+ table.insert(pieces, "-")
737
+ end
738
+ table.insert(pieces, TimeDurationUtils._formatTokenValue(part, padded, part.rank == smallestRank, options))
739
+ end
740
+ end
741
+
742
+ return table.concat(pieces)
743
+ end
744
+
745
+ -- Picks a template from the duration's size, the way a person would write it
746
+ function TimeDurationUtils._defaultTemplate(totalMilliseconds: number): (string, DurationTrim)
747
+ local breakdown: any = TimeDurationUtils.toTable(totalMilliseconds / 1000)
748
+ local largest, smallest
749
+ for _, field in { "years", "months", "days", "hours", "minutes", "seconds", "milliseconds" } do
750
+ if breakdown[field] ~= 0 then
751
+ largest = largest or field
752
+ smallest = field
753
+ end
754
+ end
755
+
756
+ if largest == nil then
757
+ return "s __", "large" :: DurationTrim
758
+ elseif largest == "milliseconds" then
759
+ return "S __", "large" :: DurationTrim
760
+ elseif largest == "seconds" or largest == "minutes" then
761
+ return "*m:ss", "large" :: DurationTrim
762
+ elseif largest == "hours" then
763
+ return "h:mm:ss", "large" :: DurationTrim
764
+ elseif largest == "days" then
765
+ if smallest == "days" then
766
+ return (if breakdown.days % 7 == 0 then "w __" else "d __"), "large" :: DurationTrim
767
+ end
768
+ return "w __, d __, h __", "both" :: DurationTrim
769
+ elseif largest == smallest then
770
+ return (if largest == "years" then "y __" else "M __"), "large" :: DurationTrim
771
+ else
772
+ return "y __, M __, d __", "both" :: DurationTrim
773
+ end
774
+ end
775
+
776
+ --[=[
777
+ Formats the duration with a template in the style of moment-duration-format. Tokens are `y`
778
+ years, `M` months, `w` weeks, `d` days, `h` hours, `m` minutes, `s` seconds, `C`
779
+ centiseconds and `S` milliseconds; repeating a letter zero pads it to that width. The largest token in the
780
+ template absorbs everything above it, so `h:mm` on 47 hours is `47:00`, and the smallest
781
+ token is rounded unless `trunc` is set. `__` after a token prints it as a localized phrase
782
+ such as `2 days`, and text in square brackets is literal.
783
+
784
+ Tokens whose value is zero are dropped from the front by default, so `h:mm:ss` on 45 seconds
785
+ is `45`; see [DurationTrim]. Dropping a token also drops the text between it and its
786
+ neighbour, so put unit words in `__` labels rather than brackets when trimming matters.
787
+ Without a template, one is chosen from the duration's size: `250 milliseconds`, `2:03:00`,
788
+ `3 days`, `1 week, 3 days, 2 hours` or `1 year, 2 months, 3 days`.
789
+
790
+ ```lua
791
+ TimeDurationUtils.format(47 * 3600, "h:mm:ss") --> 47:00:00
792
+ TimeDurationUtils.format(65.432, "mm:ss:CC", { trunc = true }) --> 01:05:43
793
+ TimeDurationUtils.format({ days = 45 }, "d __") --> 45 days
794
+ TimeDurationUtils.format(123 * 60, "d __ h:mm:ss") --> 2:03:00
795
+ TimeDurationUtils.format({ days = 1, minutes = 5 }, "d __, h __, m __", { largest = 2 }) --> 1 day, 5 minutes
796
+ TimeDurationUtils.format({ hours = 2 }, "h __", { locale = "es-es" }) --> 2 horas
797
+ ```
798
+ ]=]
799
+ function TimeDurationUtils.format(duration: DurationLike, template: string?, options: DurationFormatOptions?): string
800
+ local seconds = TimeDurationUtils.toSeconds(duration)
801
+ local isNegative = seconds < 0
802
+ local totalMilliseconds = math.floor(math.abs(seconds) * 1000 + 0.5)
803
+
804
+ local resolved: DurationFormatOptions = if options then table.clone(options) else {}
805
+ local str = template
806
+ if str == nil then
807
+ local defaultTemplate: string, defaultTrim: DurationTrim = TimeDurationUtils._defaultTemplate(totalMilliseconds)
808
+ str = defaultTemplate
809
+ if resolved.trim == nil then
810
+ resolved.trim = defaultTrim
811
+ end
812
+ end
813
+
814
+ local parts = TimeDurationUtils._tokenizeTemplate(str :: string)
815
+ local shown = TimeDurationUtils._getShownTokens(parts)
816
+ assert(#shown > 0, string.format("No unit tokens in duration template %q", str :: string))
817
+
818
+ if resolved.minValue or resolved.maxValue then
819
+ local smallestMilliseconds = FORMAT_TOKENS[shown[#shown].rank :: number].milliseconds
820
+ local amount = totalMilliseconds / smallestMilliseconds
821
+ local bounded: DurationFormatOptions = table.clone(resolved)
822
+ bounded.minValue = nil
823
+ bounded.maxValue = nil
824
+
825
+ if resolved.minValue and amount < resolved.minValue then
826
+ return "< " .. TimeDurationUtils.format(resolved.minValue * smallestMilliseconds / 1000, str, bounded)
827
+ elseif resolved.maxValue and amount > resolved.maxValue then
828
+ return "> " .. TimeDurationUtils.format(resolved.maxValue * smallestMilliseconds / 1000, str, bounded)
829
+ end
830
+ end
831
+
832
+ TimeDurationUtils._assignValues(parts, totalMilliseconds, resolved)
833
+ TimeDurationUtils._applyLimits(parts, totalMilliseconds, resolved)
834
+ TimeDurationUtils._trimParts(parts, resolved)
835
+ -- Rounding lands on the smallest token still shown
836
+ TimeDurationUtils._assignValues(parts, totalMilliseconds, resolved)
837
+
838
+ return TimeDurationUtils._renderParts(parts, isNegative, resolved)
839
+ end
840
+
841
+ --[=[
842
+ Describes the duration in words through [RelativeTimeUtils]:
843
+ `an hour`, `2 days`. With `withSuffix`, a positive duration reads `in an hour` and a negative
844
+ one `an hour ago`. `options` can set the locale, thresholds or strings; its `withoutSuffix`
845
+ is ignored in favour of `withSuffix`.
846
+ ]=]
847
+ function TimeDurationUtils.humanize(
848
+ duration: DurationLike,
849
+ withSuffix: boolean?,
850
+ options: RelativeTimeUtils.RelativeTimeOptions?
851
+ ): string
852
+ local now = DateTime.now()
853
+ local later = DateTime.fromUnixTimestampMillis(now.UnixTimestampMillis + TimeDurationUtils.toMilliseconds(duration))
854
+
855
+ local resolved: RelativeTimeUtils.RelativeTimeOptions = if options then table.clone(options) else {}
856
+ resolved.withoutSuffix = not withSuffix
857
+
858
+ return RelativeTimeUtils.from(later, now, resolved)
859
+ end
860
+
861
+ --[=[
862
+ Formats the duration as an ISO 8601 string such as `P1DT12H` or `PT1.5S`. A zero duration is `P0D` and a negative one is prefixed with `-`.
863
+ ]=]
864
+ function TimeDurationUtils.toIsoString(duration: DurationLike): string
865
+ local breakdown = TimeDurationUtils.toTable(duration)
866
+ local isNegative = TimeDurationUtils.toSeconds(duration) < 0
867
+
868
+ local years = math.abs(breakdown.years)
869
+ local months = math.abs(breakdown.months)
870
+ local days = math.abs(breakdown.days)
871
+ local hours = math.abs(breakdown.hours)
872
+ local minutes = math.abs(breakdown.minutes)
873
+ local seconds = math.abs(breakdown.seconds) + math.abs(breakdown.milliseconds) / 1000
874
+ seconds = math.floor(seconds * 10000 + 0.5) / 10000
875
+
876
+ local date = (if years ~= 0 then years .. "Y" else "")
877
+ .. (if months ~= 0 then months .. "M" else "")
878
+ .. (if days ~= 0 then days .. "D" else "")
879
+ local time = (if hours ~= 0 then hours .. "H" else "")
880
+ .. (if minutes ~= 0 then minutes .. "M" else "")
881
+ .. (if seconds ~= 0 then seconds .. "S" else "")
882
+
883
+ if date == "" and time == "" then
884
+ return "P0D"
885
+ end
886
+
887
+ return (if isNegative then "-" else "") .. "P" .. date .. (if time ~= "" then "T" .. time else "")
888
+ end
889
+
890
+ return TimeDurationUtils