From 4701b125596e7f9da31a9f0954f22b018a4994cf Mon Sep 17 00:00:00 2001 From: Jason Woofenden Date: Thu, 1 Apr 2010 07:43:49 -0400 Subject: [PATCH] added ordinalize() and tests for it --- misc.php | 29 ++++++++++++++++++++++++++ unit_tests.php | 2 +- unit_tests/misc.php | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 unit_tests/misc.php diff --git a/misc.php b/misc.php index 8f46014..1045d45 100644 --- a/misc.php +++ b/misc.php @@ -15,6 +15,35 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +# pass an integer, returns the suffix +function ordinal_suffix($i) { + # teens are all __th + if(strlen($i) > 1 && substr($i, -2, 1) === '1') { + return 'th'; + } + switch(substr($i, -1)) { + case '': + return ''; + case '1': + return 'st'; + case '2': + return 'nd'; + case '3': + return 'rd'; + default; + return 'th'; + } +} + +# ordinalize(1) => "1st" +# ordinalize(2) => "2nd" +# ordinalize(3) => "3rd" +# ordinalize(111) => "111th" +# ordinalize("62") => "62nd" +function ordinalize($i) { + return $i . ordinal_suffix($i); +} + # returns an array containing just the elements of $pipes that are readable (without blocking) # timeout 0 means don't wait, timeout NULL means wait indefinitely function readable_sockets($pipes, $timeout = 0){ diff --git a/unit_tests.php b/unit_tests.php index 0808fa4..97df911 100644 --- a/unit_tests.php +++ b/unit_tests.php @@ -49,7 +49,7 @@ function run_unit_tests($directory, $basenames) { # Call this to unit test wfpl. By default it tests everything, or you can pass # a space-separated list of the basenames of the files in code/wfpl/unit_tests/ # that you'd like to run. -function unit_test_wfpl($basenames = 'format db') { +function unit_test_wfpl($basenames = 'format db misc') { tem_load('code/wfpl/unit_tests/template.html'); run_unit_tests('code/wfpl/unit_tests', $basenames); display_messages(); diff --git a/unit_tests/misc.php b/unit_tests/misc.php new file mode 100644 index 0000000..0582649 --- /dev/null +++ b/unit_tests/misc.php @@ -0,0 +1,56 @@ +. + + +# This file contains tests for functions in code/wfpl/misc.php +# +# See code/wfpl/unit_tests.php for details on how to run or create tests + + +require_once('code/wfpl/misc.php'); + +# returns number of errors +function test_ordinalize() { + $errors = 0; + + $tests = array( + '', '', + 0, "0th", + 1, "1st", + 2, "2nd", + 3, "3rd", + 111, "111th", + "62", "62nd"); + for($i = 0; $i < count($tests); $i += 2) { + $arg = $tests[$i]; + $correct = $tests[$i + 1]; + $ret = ordinalize($arg); + if($ret !== $correct) { + message("ordinalize($arg) returned \"$ret\" instead of \"$correct\""); + $errors += 1; + } + } + + return $errors; +} + +# returns number of errors +function misc_unit_tests_main() { + $errors = 0; + $errors += test_ordinalize(); + return $errors; +} -- 1.7.10.4