From e73b6823eddb8d31c2fd3a98ff87e5980657a68f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefanos=20Carlstr=C3=B6m?= Date: Tue, 4 May 2021 08:51:19 +0200 Subject: [PATCH] Implemented clamp(t, i::ClosedInterval) (#77) --- Project.toml | 2 +- src/IntervalSets.jl | 10 +++++++++- test/runtests.jl | 7 +++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Project.toml b/Project.toml index 60ac6a4..d06f201 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "IntervalSets" uuid = "8197267c-284f-5f27-9208-e0e47529a953" -version = "0.5.3" +version = "0.5.4" [deps] Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" diff --git a/src/IntervalSets.jl b/src/IntervalSets.jl index c35f590..3f2b0e6 100644 --- a/src/IntervalSets.jl +++ b/src/IntervalSets.jl @@ -2,7 +2,7 @@ module IntervalSets using Base: @pure import Base: eltype, convert, show, in, length, isempty, isequal, issubset, ==, hash, - union, intersect, minimum, maximum, extrema, range, ⊇ + union, intersect, minimum, maximum, extrema, range, clamp, ⊇ using Statistics import Statistics: mean @@ -270,6 +270,14 @@ range(i::TypedEndpointsInterval{:closed,:open}; length::Integer) = range(leftendpoint(i); step=width(i)/length, length=length) range(i::TypedEndpointsInterval{:closed,:open}, len::Integer) = range(i; length=len) +""" + clamp(t, i::ClosedInterval) + +Clamp the scalar `t` such that the result is in the interval `i`. +""" +clamp(t, i::TypedEndpointsInterval{:closed,:closed}) = + clamp(t, leftendpoint(i), rightendpoint(i)) + """ duration(iv) diff --git a/test/runtests.jl b/test/runtests.jl index 7d69c2d..e5a4019 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -705,6 +705,13 @@ struct IncompleteInterval <: AbstractInterval{Int} end @test range(Interval{:closed,:open}(0..1); length=10) == range(0; step=1/10, length=10) end + @testset "clamp" begin + @test clamp(1, 0..3) == 1 + @test clamp(1.0, 1.5..3) == 1.5 + @test clamp(1.0, 0..0.5) == 0.5 + @test clamp.([pi, 1.0, big(10.)], Ref(2..9.)) == [big(pi), 2, 9] + end + @testset "IteratorSize" begin @test Base.IteratorSize(ClosedInterval) == Base.SizeUnknown() end