Skip to content

Instantly share code, notes, and snippets.

@robertdfrench
Created July 11, 2019 23:44
Show Gist options
  • Save robertdfrench/29b59f5e7245710b9f36fa46f5938ee7 to your computer and use it in GitHub Desktop.
Save robertdfrench/29b59f5e7245710b9f36fa46f5938ee7 to your computer and use it in GitHub Desktop.
Flatten an arbitrarily-nested array of integers
#!/bin/bash
pad_response_in_brackets() {
echo -n "["
cat < /dev/stdin
echo "]"
}
strip_brackets() {
gsed 's/\[//g' | gsed 's/\]//g'
}
flatten() {
list=$* # Interpret the list of ints as a string
echo -n $list | strip_brackets | pad_response_in_brackets
}
## Unit Tests
# For each test, we run an action and "grep" for its expected output. Should one
# of the actions produce an incorrect output, grep will fail and the tests will
# stop.
set -e # Exit immediately if one of the tests fails
### test pad_response_in_brackets
echo -n "x" | pad_response_in_brackets | grep [x]
### test strip_brackets
echo -n "[1,[2,[3]]]" | strip_brackets | grep "1,2,3"
### test flatten
flatten [1,2,3] | grep [1,2,3]
flatten [1,2,[3]] | grep [1,2,3]
flatten [1,[2,[3]]] | grep [1,2,3]
flatten [[1,2,[3]],4] | grep [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment