Skip to content

Commit

Permalink
Merge pull request #28 from NicholasWMRitchie/equality
Browse files Browse the repository at this point in the history
Adds efficient isequal(), isless(), hash() and eachindex()
  • Loading branch information
stevengj authored Dec 20, 2019
2 parents 060c572 + 57f1a0f commit 93fdeb4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/PeriodicTable.jl
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,20 @@ function Base.show(io::IO, ::MIME"text/plain", e::Elements)
end
end

# Since Element equality is determined by atomic number alone...
Base.isequal(elm1::Element, elm2::Element) = elm1.number == elm2.number

# There is no need to use all the data in Element to calculated the hash
# since Element equality is determined by atomic number alone.
Base.hash(elm::Element, h::UInt) = hash(elm.number, h)

# Compare elements by atomic number to produce the most common way elements
# are sorted.
Base.isless(elm1::Element, elm2::Element) = elm1.number < elm2.number

# Provide a simple way to iterate over all elements.
Base.eachindex(elms::Elements) = eachindex(elms.data)

include("elements.jl")
const elements = Elements(_elements_data)

Expand Down
26 changes: 26 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,29 @@ end

@test_throws ErrorException O.name = "Issue21"
@test O.name == "Oxygen"

@test isless(elements[28], elements[29])
@test !isless(elements[88], elements[88])
@test !isless(elements[92], elements[90])
@test isequal(elements[38], elements[38])
@test !isequal(elements[38], elements[39])

@test elements[28] < elements[29]
@test ! (elements[88] < elements[88])
@test ! (elements[92] < elements[90])
@test elements[92] > elements[91]
@test !(elements[92] > elements[92])
@test !(elements[92] > elements[93])
@test elements[90] <= elements[91]
@test elements[91] <= elements[91]
@test !(elements[92] <= elements[91])
@test elements[38] == elements[38]
@test elements[38] elements[39]

# Ensure that the hashcode works in Dict{}
elmdict = Dict{Element,Int}( elements[z] => z for z in eachindex(elements))
@test length(elmdict) == 119
for z in eachindex(elements)
@test haskey(elmdict, elements[z])
@test elmdict[elements[z]] == z
end

0 comments on commit 93fdeb4

Please sign in to comment.