Task

The goal is to create an associative array (also known as a dictionary, map, or hash).



Related tasks:

 Associative arrays/Iteration
 Hash from two arrays


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


global values$, keys$
dim values$[1]
dim keys$[1]
 
call updateKey("a","apple")
call updateKey("b","banana")
call updateKey("c","cucumber")
 
gosub show
 
print "I like to eat a " + getValue$("c") + " on my salad."
 
call deleteKey("b")
call updateKey("c","carrot")
call updateKey("e","endive")
gosub show
 
end
 
show:
for t = 0 to countKeys()-1
   print getKeyByIndex$(t) + " " + getValueByIndex$(t)
next t
print
return
 
subroutine updateKey(key$, value$)
   # update or add an item
   i=findKey(key$)
   if i=-1 then
      i = freeKey()
      keys$[i] = key$
   end if
   values$[i] = value$
end subroutine
 
subroutine deleteKey(key$)
   # delete by clearing the key
   i=findKey(key$)
   if i<>-1 then
      keys$[i] = ""
   end if
end subroutine
 
function freeKey()
   # find index of a free element in the array
   for n = 0 to keys$[?]-1
      if keys$[n]="" then return n
   next n
   redim keys$[n+1]
   redim values$[n+1]
   return n
end function
 
function findKey(key$)
   # return index or -1 if not found
   for n = 0 to keys$[?]-1
      if key$=keys$[n] then return n
   next n
   return -1
end function
 
function getValue$(key$)
   # return a value by the key or "" if not existing
   i=findKey(key$)
   if i=-1 then
      return ""
   end if
   return values$[i]
end function
 
function countKeys()
   # return number of items
   # remember to skip the empty keys (deleted ones)
   k = 0
   for n = 0 to keys$[?] -1
      if keys$[n]<>"" then k++
   next n
   return k
end function
 
function getValueByIndex$(i)
   # get a value by the index
   # remember to skip the empty keys (deleted ones)
   k = 0
   for n = 0 to keys$[?] -1
      if keys$[n]<>"" then
         if k=i then return values$[k]
         k++
      endif
   next n
   return ""
end function
 
function getKeyByIndex$(i)
   # get a key by the index
   # remember to skip the empty keys (deleted ones)
   k = 0
   for n = 0 to keys$[?] -1
      if keys$[n]<>"" then
         if k=i then return keys$[k]
         k++
      endif
   next n
   return ""
end function