Skip to content

Commit

Permalink
Add sort capability to array_equal.
Browse files Browse the repository at this point in the history
  • Loading branch information
marshall-mcmullen committed Dec 5, 2024
1 parent d3ed5a0 commit bdc3f2d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
7 changes: 7 additions & 0 deletions share/array.sh
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ array_equal()
{
$(opt_parse \
"+verbose v | Enable verbose mode to show which elements differ." \
"+sort s | Sort both arrays before comparision." \
"__array1 | First array for comparison." \
"__array2 | Second array for comparison." \
)
Expand All @@ -387,6 +388,12 @@ array_equal()
return 1
fi

# Optionally sort the arrays before comparision.
if [[ "${sort}" -eq 1 ]]; then
array_sort __array1
array_sort __array2
fi

# We don't want to simply try to join the arrays into a single string and check that for equality as that could
# result in incorrect behavior with certain input values, e.g. array1=( "a 1 a" "1") array2=( "a 1" "a 1" ). And we
# can't just iterate over the indexes directly as the arrays could be holey (e.g. after an unset or a remove
Expand Down
9 changes: 9 additions & 0 deletions tests/array.etest
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,15 @@ ETEST_array_equal()
array_equal array1 array2
}

ETEST_array_equal_sort()
{
local array1=( {a..z} )
local array2=( {z..a} )
etestmsg "Comparing $(lval array1 array2)"

array_equal --sort array1 array2
}

ETEST_array_equal_spaces()
{
local array1=("a 1" "b 2" "c 3" "d 4")
Expand Down

0 comments on commit bdc3f2d

Please sign in to comment.