From 4c0952adc724181c0e041cdd2a4fc3ff4eed9356 Mon Sep 17 00:00:00 2001 From: Matthias Kruk Date: Tue, 29 Jun 2021 06:57:38 +0900 Subject: [PATCH] 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. --- include/array.sh | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) 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 +} -- 2.47.3