nice new tool to show version of feisty meow
[feisty_meow.git] / scripts / testing / test_assoc_array.sh
1 #!/bin/bash
2
3 ##############
4
5 # simple examples...
6
7 declare -A snuggles
8   # make an associative array
9
10 snuggles=([book]=petunia [muffets]="glasgow robbery")
11   # keys: book and muffets
12   # values: (second part)
13
14 snuggles+=([morgower]=flimshaw)
15   # adding entries to it.
16
17 echo ${!snuggles[x]}
18   # show index x's key.
19
20 echo ${snuggles[x]}
21   # show index x's value.
22
23 ##############
24
25 # excellent code from:
26 # http://blog.spencertipping.com/2009/08/constant-time-associative-arrays-in-bash
27  
28 typeset -a table_keys
29 typeset -a table_values
30  
31 function index_of_key () {
32   initial=$(($(echo $1 | md5sum | cut -c 18-32 | awk '{print "0x"$1}')))
33   while [[ ${table_keys[$initial]} && ${table_keys[$initial]} != $1 ]]; do
34     initial=$((initial + 1))
35   done
36   echo -n $initial
37 }
38  
39 function associate () {
40   index=$(index_of_key $1)
41   table_keys[$index]=$1
42   table_values[$index]=$2
43   echo -n $2
44 }
45  
46 function lookup () {
47   index=$(index_of_key $1)
48   echo -n ${table_values[$index]}
49 }
50  
51 echo Associating foo with bar and bif with baz
52 associate foo bar && echo
53 associate bif baz && echo
54  
55 echo -n Looking up foo:
56 lookup foo && echo
57  
58 echo -n Looking up bif:
59 lookup bif && echo
60  
61 echo -n Looking up bar:
62 lookup bar && echo
63
64 ##############
65