diff --git a/bash.sh b/bash.sh index 907b628..3d33bc8 100755 --- a/bash.sh +++ b/bash.sh @@ -53,14 +53,34 @@ array_filter() { # # Join array elements with a string. # -# $1: String separator -# $@: Array elements +# $1: String default, used in case array to join is empty +# $2: String separator, has to be a single element +# $@: Array elements, empty elements will be skipped # -array_join() { - local sep=$1; shift - IFS=$sep eval 'echo "$*"' + +join() { + local -a args + local default + local ifs + local IFS + + default="$1"; shift + + ifs="$1"; shift + + [ "${#ifs}" -gt 1 ] && exit 1 + + # read into array, ifs is still a space + read -r -a args <<< "$*" + + IFS="$ifs" + # args will be unbound if no more arguments were passed in + # check for that, use default if necessary + # otherwise dump the string with overwritten ifs + [ -z "${args-}" ] && echo "$default" || echo "${args[*]}" } + ################ # Benchmarking # ################ diff --git a/test-bash.sh b/test-bash.sh index dfe5633..b29301d 100755 --- a/test-bash.sh +++ b/test-bash.sh @@ -44,6 +44,70 @@ test_resolve_symlinks() { [ "$(resolve_symlinks /tmp/1/2/foo)" == "/tmp/foo" ] } +test_join_standard() { + local result + + result=$(join "def" - 1 2 3) + + [ "$result" == "1-2-3" ] +} + +test_join_one() { + local result + + result=$(join "def" - 1) + + [ "$result" == "1" ] +} + +test_join_spaces() { + local result + + result=$(join "def" - 1 '' '' 3) + + [ "$result" == "1-3" ] +} + +test_join_more_spaces() { + local result + + result=$(join "def" - 1 3) + + [ "$result" == "1-3" ] +} + +test_join_other_delimeter() { + local result + + result=$(join "def" "b" 1 3) + + [ "$result" == "1b3" ] +} + +test_join_invalid_delimeter() { + local result + + result=$(join "def" "bb" 1 3) + + [ "$?" == 1 ] +} + +test_join_no_delimeter() { + local result + + result=$(join "def") + + [ "$result" == "def" ] +} + +test_join_default() { + local result + + result=$(join "def" - '' '') + + [ "$result" == "def" ] +} + tests() { local ret=0 local test_log="/tmp/${0##*/}.test.log"