rubyx/lib/parfait/dictionary.rb

101 lines
1.9 KiB
Ruby
Raw Normal View History

# almost simplest hash imaginable. make good use of Lists
module Parfait
class Dictionary < Object
2015-05-20 12:50:56 +02:00
# only empty initialization for now
#
# internally we store keys and values in lists, which means this does **not** scale well
def initialize
2015-05-21 20:50:17 +02:00
super()
@keys = List.new()
@values = List.new()
end
2015-05-20 12:50:56 +02:00
def keys
@keys.dup
end
def values
@values.dup
end
2015-05-20 12:50:56 +02:00
# are there any key/value items in the list
def empty?
@keys.empty?
end
2015-05-20 12:50:56 +02:00
# How many key/value pairs there are
def length()
return @keys.get_length()
end
def next_value(val)
return @values.next_value(val)
end
2015-05-20 12:50:56 +02:00
# get a value fot the given key
2015-05-25 17:48:35 +02:00
# key identity is checked with == not === (ie equals not identity)
2015-05-20 12:50:56 +02:00
# return nil if no such key
def get(key)
index = key_index(key)
if( index )
@values.get(index)
else
nil
end
end
2015-05-20 12:50:56 +02:00
# same as get(key)
def [](key)
get(key)
end
2015-05-20 12:50:56 +02:00
# private method
def key_index(key)
@keys.index_of(key)
end
2015-05-20 12:50:56 +02:00
# set key with value, returns value
def set(key , value)
index = key_index(key)
if( index )
@values.set(index , value)
else
@keys.push(key)
@values.push(value)
end
value
end
2015-05-20 12:50:56 +02:00
#same as set(k,v)
def []=(key,val)
set(key,val)
end
2015-05-20 12:50:56 +02:00
# yield to each key value pair
2015-05-20 09:57:20 +02:00
def each
index = 0
while index < @keys.get_length
key = @keys.get(index)
value = @values.get(index)
2015-05-20 09:57:20 +02:00
yield key , value
index = index + 1
end
self
end
2016-12-08 11:48:08 +01:00
def inspect
string = "Dictionary{"
each do |key , value|
string += key.to_s + " => " + value.to_s + " ,"
end
string + "}"
end
def to_rxf_node(writer , level , ref)
Sof.hash_to_rxf_node( self , writer , level , ref)
end
2014-09-16 15:05:38 +02:00
end
end