Skip to content

Instantly share code, notes, and snippets.

@ekinakyurek ekinakyurek/IndexedDict.jl
Last active Jan 25, 2019

Embed
What would you like to do?
IndexedDict
import Base: get, length, getindex, push!, append!
struct IndexedDict{T}
toIndex::Dict{T,Int};
toElement::Vector{T};
IndexedDict{T}(toIndex,toElement) where T = new(toIndex,toElement)
IndexedDict{T}(toIndex,toElement) where T<:Integer = error("Cannot Create IndexedDict of Integers")
IndexedDict{T}(toIndex,toElement) where T<:AbstractArray = error("Cannot Create IndexedDict of Arrays")
end
IndexedDict{T}() where T = IndexedDict{T}(Dict{T,Int}(),T[])
function IndexedDict(toElement::Vector{T}) where T
toIndex=Dict{T,Int}(v=>k for (k,v) in enumerate(toElement))
IndexedDict(toIndex, toElement)
end
function IndexedDict(toIndex::Dict{T,Int}) where T
toElement=Vector{T}(undef,length(toIndex))
for (k,v) in toIndex; toElement[v]=k; end
IndexedDict{T}(toIndex,toElement)
end
get(d::IndexedDict,v,default) = get(d.toIndex,v,default)
length(d::IndexedDict) = length(d.toElement)
getindex(d::IndexedDict,inds::Integer) = d.toElement[inds]
getindex(d::IndexedDict{T},inds::T) where T = d.toIndex[inds]
getindex(d::IndexedDict{T}, elements::Array{T,1}) where T = map(e->d[e], elements)
getindex(d::IndexedDict, inds::Array{<:Integer,1}) = d.toElement[inds]
append!(d1::IndexedDict{T}, d2::IndexedDict{T}) where T = append!(d1,d2.toElement)
function push!(d::IndexedDict, element)
if !haskey(d.toIndex,element)
d.toIndex[element]=length(d)+1;
push!(d.toElement,element)
end
return d
end
function append!(d::IndexedDict, elements)
for element in elements
push!(d,element)
end
return d
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.