Browse Source

no need for associative array

main
pvincent 6 days ago
parent
commit
a3b83ce4ed
  1. 76
      test/associative.test.bash

76
test/associative.test.bash

@ -12,45 +12,18 @@ function array_new {
} }
function array_inspect { function array_inspect {
local -n ref="$1"
local ref prefix i
declare -n ref="$1"
prefix="${2:-}" prefix="${2:-}"
echo "${prefix}array '$1' contains ${#ref[@]} elements" echo "${prefix}array '$1' contains ${#ref[@]} elements"
local i
for i in "${ref[@]}"; do echo "${prefix}-> $i"; done
echo "${prefix}----"
}
function nested_new {
local internal
ref_name="$1"
shift
[[ -v nested_count ]] && ((nested_count++)) || nested_count=1
nested_name="nested_$nested_count"
declare -gA "$nested_name"
declare -gn "$ref_name"="$nested_name"
declare -n internal="$nested_name"
internal['TYPE']='NESTED_ARRAY'
local i=0
local j=0
for j in "$@"; do
internal["$i"]="$j"
i=$((i + 1))
for i in "${ref[@]}"; do
if [[ -R $i ]]; then
array_inspect "$i" "${prefix} => "
else
echo "${prefix}-> $i"
fi
done done
}
function nested_inspect {
local internal
declare -n internal=$1
[[ "${internal['TYPE']}" != 'NESTED_ARRAY' ]] && >&2 echo "expected nested array: $1" && return 1
count=${#internal[@]}
count=$((count - 1))
echo "nested '$1' contains $count arrays"
local i
for ((i = 0; i < count; i++)); do
array_inspect "${internal[$i]}" " => "
done
echo ----
echo "${prefix}----"
} }
# initialization # initialization
@ -58,16 +31,29 @@ array_new mine1 'Albert' 20
array_new mine2 'Bob' 24 array_new mine2 'Bob' 24
array_new mine3 'Conrad' 31 true array_new mine3 'Conrad' 31 true
array_new nested mine1 mine2 mine3
array_inspect nested
# change values # change values
mine1+=(false) mine1+=(false)
: "$mine3" # pseudo use fix shellcheck issue : "$mine3" # pseudo use fix shellcheck issue
mine3[1]=$((mine3[1] + 8))
mine3[2]=false mine3[2]=false
nested_new nested1 mine1 mine2 mine3
nested_inspect nested1
# change nested values
declare -n first="${nested1[0]:?}" # ':?' fix shellcheck issue
first+=("nope")
first[1]=$((first[1] + 5))
nested_inspect nested1
array_inspect nested
# nested twice
declare -n other="${nested[1]:?}" # ':?' fix shellcheck issue
: "${other}" # pseudo use fix shellcheck issue
array_inspect other
array_new mine4 'Darryl' 30
other+=(mine4)
array_inspect nested
# nested_new nested1 mine1 mine2 mine3
# nested_inspect nested1
#
# # change nested values
# declare -n first="${nested1[0]:?}" # ':?' fix shellcheck issue
# first+=("nope")
# first[1]=$((first[1] + 5))
# nested_inspect nested1
Loading…
Cancel
Save