Created
September 26, 2022 12:08
-
-
Save wperron/91c64c868c99b89cdc4f7019e88614ec to your computer and use it in GitHub Desktop.
Return a string corresponding to the ordinal of the given integer using Rust's pattern matching
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
fn main() { | |
println!("Hello, world!"); | |
} | |
pub fn ordinal(num: isize) -> String { | |
let one = num % 10; | |
let ten = (num / 10) % 10; | |
match (one, ten) { | |
(o, t) if t == 1 && o > 0 && 0 <= 3 => format!("{}th", num), | |
(1, _) => format!("{}st", num), | |
(2, _) => format!("{}nd", num), | |
(3, _) => format!("{}rd", num), | |
(_, _) => format!("{}th", num), | |
} | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn test_ordinal() { | |
assert_eq!("1st", ordinal(1)); | |
assert_eq!("2nd", ordinal(2)); | |
assert_eq!("3rd", ordinal(3)); | |
assert_eq!("4th", ordinal(4)); | |
assert_eq!("6th", ordinal(6)); | |
assert_eq!("7th", ordinal(7)); | |
assert_eq!("10th", ordinal(10)); | |
assert_eq!("11th", ordinal(11)); | |
assert_eq!("12th", ordinal(12)); | |
assert_eq!("13th", ordinal(13)); | |
assert_eq!("21st", ordinal(21)); | |
assert_eq!("22nd", ordinal(22)); | |
assert_eq!("23rd", ordinal(23)); | |
assert_eq!("111th", ordinal(111)); | |
assert_eq!("112th", ordinal(112)); | |
assert_eq!("913th", ordinal(913)); | |
assert_eq!("10012th", ordinal(10012)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment