Skip to content

Commit

Permalink
Add length (#23)
Browse files Browse the repository at this point in the history
See discussion at
#21, this should
fix the issue.
  • Loading branch information
tpapp authored and timholy committed Oct 20, 2017
1 parent 77d4bf0 commit 56e1d8e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/closed.jl
Expand Up @@ -94,10 +94,15 @@ 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

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)}

7 changes: 7 additions & 0 deletions test/runtests.jl
Expand Up @@ -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

Expand Down

0 comments on commit 56e1d8e

Please sign in to comment.