Functional Weave
Code in TypeScript

monitor.format-duration@1.0.0

README.md

1,226 bytes · view raw

# monitor.format-duration

A number of seconds as the short duration a dashboard or alert shows:
`"3h 12m"`, `"2d 4h"`, `"45s"`, `"0s"`. Units are days, hours, minutes and
seconds (`d h m s`); days never roll up into weeks or years, because months
and years have no fixed length (400 days is `"400d"`).

## The rule

1. Find the largest unit that is not zero.
2. Look at `maxUnits` consecutive units from there, down to seconds at most.
3. Show the non-zero ones among them, separated by a space.

So zeros in between are dropped (`3605` with 3 units is `"1h 5s"`, not
`"1h 0m 5s"`), and a unit beyond the window is never shown however large
(`3605` with 2 units is `"1h"`: minutes are zero and seconds are beyond the
precision asked for). The result is always truncated, never rounded up: a
duration is never displayed longer than it was, so `86399` with one unit is
`"23h"`, not `"1d"`.

Zero is `"0s"`, never an empty string.

`time.duration` also formats durations, but in whole minutes with no spaces
(`"2h15m"`); this one is the second-resolution format monitoring tools use.

## Errors

- `seconds must be a whole number, received X`
- `seconds must not be negative, received X`
- `maxUnits must be 1 to 4, received X`