Skip to content

Commit 728b83b

Browse files
committed
nearest can deal with units
1 parent 6f8f87f commit 728b83b

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ This page describes the most important changes in `TypeUtils`. The format is bas
1111
- With multiple arguments, `get_precision(x, y...)` yields the best precision of all the
1212
given arguments.
1313

14+
- `nearest(T, x)` can deal with dimensionful numbers and types.
15+
1416

1517
## Version 1.9.0 (2025-06-20)
1618

ext/TypeUtilsUnitfulExt.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,10 @@ TypeUtils.adapt_precision(::Type{T}, x::Quantity{S,D,U}) where {T<:Precision,D,U
3333
TypeUtils.adapt_precision(::Type{T}, ::Type{Quantity{S,D,U}}) where {T<:Precision,S,D,U} =
3434
Quantity{adapt_precision(T, S), D, U}
3535

36+
TypeUtils.nearest(::Type{Q}, x::Q) where {T,D,U,Q<:AbstractQuantity{T,D,U}} = x
37+
TypeUtils.nearest(::Type{Q}, x::AbstractQuantity{<:Any,D,U}) where {T,D,U,Q<:AbstractQuantity{T,D,U}} =
38+
nearest(T, ustrip(x))*unit(x)
39+
TypeUtils.nearest(::Type{Q}, x::Number) where {T,D,U,Q<:AbstractQuantity{T,D,U}} =
40+
nearest(Q, uconvert(unit(Q), x))
41+
3642
end # module

test/runtests.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,12 @@ same_value_and_type(x::T, y::T) where {T} = (x === y) || (x == y)
266266
let vals = (1.3, -2.7, pi, 42)
267267
@test map(nearest(Int), vals) === map(x -> nearest(Int, x), vals)
268268
end
269+
# `nearest` with dimensionful numbers.
270+
@test @inferred(nearest(typeof(1.0u"m"), -2.3u"m")) === -2.3u"m"
271+
@test @inferred(nearest(typeof(1u"cm"), -2.3u"m")) === -230u"cm"
272+
@test @inferred(nearest(typeof(1u"mm"), -2.3u"m")) === -2300u"mm"
273+
@test_throws Unitful.DimensionError @inferred(nearest(typeof(1u"mm"), 81.0u"m/s"))
274+
@test @inferred(nearest(typeof(1u"mm/s"), 871.0u"m/hr")) === 242u"mm/s"
269275
end
270276

271277
@testset "Array axes and size" begin

0 commit comments

Comments
 (0)