From b742e6af12cb4f98f6398bc6f67ca53a08dd3920 Mon Sep 17 00:00:00 2001 From: "Tamas K. Papp" Date: Wed, 16 Nov 2016 10:52:58 +0100 Subject: [PATCH] Added width (with tests). Trivial addition for the width of the interval. Implementation also handles case when type of the width is different from the eltype (eg ClosedInterval{Date}). --- src/IntervalSets.jl | 2 +- src/closed.jl | 5 +++++ test/runtests.jl | 6 ++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/IntervalSets.jl b/src/IntervalSets.jl index 4625743..50d3c21 100644 --- a/src/IntervalSets.jl +++ b/src/IntervalSets.jl @@ -7,7 +7,7 @@ module IntervalSets using Base: @pure import Base: eltype, convert, show, in, length, isempty, isequal, issubset, ==, hash, union, intersect, minimum, maximum -export AbstractInterval, ClosedInterval, ⊇, .., ±, ordered +export AbstractInterval, ClosedInterval, ⊇, .., ±, ordered, width abstract AbstractInterval{T} diff --git a/src/closed.jl b/src/closed.jl index d1996f5..e86576f 100644 --- a/src/closed.jl +++ b/src/closed.jl @@ -71,3 +71,8 @@ end issubset(A::ClosedInterval, B::ClosedInterval) = ((A.left in B) && (A.right in B)) || isempty(A) ⊇(A::ClosedInterval, B::ClosedInterval) = issubset(B, A) + +function width{T}(A::ClosedInterval{T}) + _width = A.right - A.left + max(zero(_width), _width) # this works when T is a Date +end diff --git a/test/runtests.jl b/test/runtests.jl index 1c228f4..19a84f4 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -73,5 +73,11 @@ using Base.Test @test I ⊇ ClosedInterval(1, 2) @test hash(1..3) == hash(1.0..3.0) + + let A = Date(1990, 1, 1), B = Date(1990, 3, 1) + @test width(ClosedInterval(A, B)) == Base.Dates.Day(59) + @test width(ClosedInterval(B, A)) == Base.Dates.Day(0) + @test isempty(ClosedInterval(B, A)) + end end end