From: Matthias Kruk Date: Mon, 28 Jun 2021 21:57:38 +0000 (+0900) Subject: include/array: Add functions for comparing two arrays X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=4c0952adc724181c0e041cdd2a4fc3ff4eed9356;p=toolbox include/array: Add functions for comparing two arrays 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. --- diff --git a/include/array.sh b/include/array.sh index 37554c9..7008b59 100644 --- a/include/array.sh +++ b/include/array.sh @@ -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 +}