Skip to content

Commit 275a574

Browse files
committed
feat: add comparison function for Duration
`compare/2` function to the Duration module, allowing for the comparison of two Duration. The function returns `0`, `-1`, or `1` based on the equality and relative values of the durations.
1 parent 170b797 commit 275a574

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

lib/elixir/lib/calendar/duration.ex

+28
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,34 @@ defmodule Duration do
299299
}
300300
end
301301

302+
@doc """
303+
Compares two durations.
304+
305+
Returns `:eq` if the durations are equal, `:lt` if the first duration is less than the second, and `:gt` if the first
306+
duration is greater than the second.
307+
308+
## Examples
309+
310+
iex> Duration.compare(Duration.new!(second: 10), Duration.new!(second: 20))
311+
:lt
312+
iex> Duration.compare(Duration.new!(second: 20), Duration.new!(second: 10))
313+
:gt
314+
iex> Duration.compare(Duration.new!(second: 10), Duration.new!(second: 10))
315+
:eq
316+
"""
317+
@doc since: "1.19.0"
318+
@spec compare(t, t) :: :eq | :lt | :gt
319+
def compare(%Duration{} = d1, %Duration{} = d2) do
320+
d1_timeout = Kernel.to_timeout(d1)
321+
d2_timeout = Kernel.to_timeout(d2)
322+
323+
cond do
324+
d1_timeout == d2_timeout -> :eq
325+
d1_timeout < d2_timeout -> :lt
326+
d1_timeout > d2_timeout -> :gt
327+
end
328+
end
329+
302330
@doc """
303331
Parses an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) formatted duration string to a `Duration` struct.
304332

0 commit comments

Comments
 (0)