Hello!
TL;DR is it ok to unwrap the Int
value from Duration
? If not, should there be a duration.compare
function?
Given a package release date, I need to check if it was released within the last hour. I didn't find a function for comparing durations in the duration
module, so I'm wondering if there is a preferred way of doing that?
First, I chose to unwrap the underlying integer values and compare them, but I thought I shouldn't be depending on the implementation details of the Duration
type.
fn format_date(datetime: Time) -> String {
let now = birl.now()
let Duration(package_age_ms) = birl.difference(now, datetime)
let Duration(age_threshold_ms) = duration.hours(1)
case package_age_ms < age_threshold_ms {
True -> "Just now!"
False -> birl.legible_difference(now, datetime)
}
}
Then I noticed there is a blur_to
function, which lets me write less code, but its behavior is somewhat uncommon
if the duration is not an integer multiple of the unit, the remainder will be disgarded if itβs less than two thirds of the unit
fn format_date(datetime: Time) -> String {
let now = birl.now()
let package_age = birl.difference(now, datetime)
case duration.blur_to(package_age, duration.Hour) < 1 {
True -> "Just now!"
False -> birl.legible_difference(now, datetime)
}
}
Do you think adding a new function such as fn compare(a: Duration, b: Duration) -> Bool
is warranted?
Just FYI: While writing this and collecting my thoughts, I noticed the birl.compare
function and found a third solution to this
fn format_date(datetime: Time) -> String {
let now = birl.now()
let one_hour_ago = birl.subtract(now, duration.hours(1))
case birl.compare(datetime, one_hour_ago) {
order.Gt -> "Just now!"
_ -> birl.legible_difference(now, datetime)
}
}