-
Notifications
You must be signed in to change notification settings - Fork 1
Add a better version of join. #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
Skips empty arguments. Handles defaults. Has tests.
local IFS | ||
|
||
default="$1"; shift | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: remove empty line
@@ -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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Based on the principle of do one thing and do it well, can you remove the "default"?
I feel this is conflating two responsibilities into one function (join
should just join, nothing more, nothing less).
# $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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since we're making array_join
better, why don't we improve it to allow any join string, rather than just a single character?
I can imagine this is useful, e.g. say you want to create a human-readable CSV, so you want to join by ", " (comma-space).
join() { | ||
local -a args | ||
local default | ||
local ifs |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A better name for the ifs
variable here would be join_string
.
|
||
[ "$result" == "def" ] | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you add the following test for joining an element containing a newline?
test_join_multiline_string_element() {
local result
local -a test_input=(
"foo"
"bar"
"omg"$'\n'"baz"
)
result=$(join "def" "," "${test_input[@]}")
[ "$result" == "foo,bar,omg"$'\n'"baz" ]
}
The current code fails this test.
Skips empty arguments.
Handles defaults.
Has tests.