rubyx/lib/register/parfait/dictionary.rb

92 lines
1.9 KiB
Ruby
Raw Normal View History

# almost simplest hash imaginable. make good use of Lists
module Parfait
class Dictionary < Object
attribute :keys
attribute :values
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()
self.keys = List.new()
self.values = List.new()
end
2015-05-20 12:50:56 +02:00
# are there any key/value items in the list
def empty?
self.keys.empty?
end
2015-05-20 12:50:56 +02:00
# How many key/value pairs there are
def length()
return self.keys.get_length()
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 )
self.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)
len = self.keys.get_length()
2015-05-17 14:34:29 +02:00
index = 1
found = nil
2015-05-17 14:34:29 +02:00
while(index <= len)
if( self.keys.get(index) == key)
found = index
break
end
index += 1
end
found
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 )
self.keys.set(index , value)
else
self.keys.push(key)
self.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 = 1
while index <= self.keys.get_length
key = self.keys.get(index)
value = self.values.get(index)
2015-05-20 09:57:20 +02:00
yield key , value
index = index + 1
end
self
end
def to_sof_node(writer , level , ref)
Sof.hash_to_sof_node( self , writer , level , ref)
end
2014-09-16 15:05:38 +02:00
end
end