]> git.corax.cc Git - toolbox/commitdiff
include/array: Add functions for comparing two arrays
authorMatthias Kruk <m@m10k.eu>
Mon, 28 Jun 2021 21:57:38 +0000 (06:57 +0900)
committerMatthias Kruk <m@m10k.eu>
Mon, 28 Jun 2021 21:57:38 +0000 (06:57 +0900)
This commit adds the array_same() and array_identical() functions to
the array module. The former allows the caller to determine if two
arrays contain the same elements (i.e. permutations are accepted)
while the latter function does not permit permutations.

include/array.sh

index 37554c97ddf3c4ae752bf7f3fd38188108041408..7008b59a7de976c7936870c3ac91527e7f34505c 100644 (file)
@@ -49,3 +49,47 @@ array_sort() {
 
        array_to_lines "${array[@]}" | sort -V
 }
+
+array_same() {
+       local -n _array_same_left="$1"
+       local -n _array_same_right="$2"
+
+       local element
+
+       if (( ${#_array_same_left[@]} != ${#_array_same_right[@]} )); then
+               return 1
+       fi
+
+       for element in "${_array_same_left[@]}"; do
+               if ! array_contains "$element" "${_array_same_right[@]}"; then
+                       return 1
+               fi
+       done
+
+       for element in "${_array_same_right[@]}"; do
+               if ! array_contains "$element" "${_array_same_left[@]}"; then
+                       return 1
+               fi
+       done
+
+       return 0
+}
+
+array_identical() {
+       local -n _array_identical_left="$1"
+       local -n _array_identical_right="$2"
+
+       local i
+
+       if (( ${#_array_identical_left[@]} != ${#_array_identical_right[@]} )); then
+               return 1
+       fi
+
+       for (( i = 0; i < ${#_array_identical_left[@]}; i++ )); do
+               if [[ "${_array_identical_left[$i]}" != "${_array_identical_right[$i]}" ]]; then
+                       return 1
+               fi
+       done
+
+       return 0
+}