Created
July 11, 2019 23:44
-
-
Save robertdfrench/29b59f5e7245710b9f36fa46f5938ee7 to your computer and use it in GitHub Desktop.
Flatten an arbitrarily-nested array of integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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