From 56e1d8e8f9c756d85d7608468cb41574c5da042b Mon Sep 17 00:00:00 2001 From: "Tamas K. Papp" Date: Fri, 20 Oct 2017 22:26:25 +0200 Subject: [PATCH] Add length (#23) See discussion at https://github.com/JuliaMath/IntervalSets.jl/issues/21, this should fix the issue. --- src/closed.jl | 5 +++++ test/runtests.jl | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/src/closed.jl b/src/closed.jl index 21e6f18..85c1ef7 100644 --- a/src/closed.jl +++ b/src/closed.jl @@ -94,6 +94,10 @@ function width{T}(A::ClosedInterval{T}) max(zero(_width), _width) # this works when T is a Date end +length{T <: Integer}(A::ClosedInterval{T}) = max(0, Int(A.right - A.left) + 1) + +length(A::ClosedInterval{Date}) = max(0, Dates.days(A.right - A.left) + 1) + function convert{R<:AbstractUnitRange,I<:Integer}(::Type{R}, i::ClosedInterval{I}) R(minimum(i), maximum(i)) end @@ -101,3 +105,4 @@ end range{I<:Integer}(i::ClosedInterval{I}) = convert(UnitRange{I}, i) Base.promote_rule{T1,T2}(::Type{ClosedInterval{T1}}, ::Type{ClosedInterval{T2}}) = ClosedInterval{promote_type(T1, T2)} + diff --git a/test/runtests.jl b/test/runtests.jl index 0ebed0e..7d8efd5 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -79,12 +79,19 @@ using Base.Test @test width(ClosedInterval(A, B)) == Base.Dates.Day(59) @test width(ClosedInterval(B, A)) == Base.Dates.Day(0) @test isempty(ClosedInterval(B, A)) + @test length(ClosedInterval(A, B)) ≡ 60 + @test length(ClosedInterval(B, A)) ≡ 0 end @test width(ClosedInterval(3,7)) ≡ 4 @test width(ClosedInterval(4.0,8.0)) ≡ 4.0 @test promote(1..2, 1.0..2.0) === (1.0..2.0, 1.0..2.0) + + @test length(I) == 4 + @test length(J) == 0 + # length deliberately not defined for non-integer intervals + @test_throws MethodError length(1.2..2.4) end end