diff --git a/src/lib.rs b/src/lib.rs index 9c81a4c..1e0d14c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,3 @@ pub mod macros; -pub mod time; \ No newline at end of file +pub mod time; +pub mod util; diff --git a/src/util.rs b/src/util.rs new file mode 100644 index 0000000..21c6074 --- /dev/null +++ b/src/util.rs @@ -0,0 +1,50 @@ +/// Returns the number with its ordinal suffix (1st, 2nd, 3rd, etc.) +/// +/// # Examples +/// +/// ``` +/// use diaryrs::util::ordinal; +/// +/// assert_eq!(ordinal(1), "1st"); +/// // Accounts for teens properly: 11th, 12th, 13th etc. +/// assert_eq!(ordinal(12), "12th"); +/// assert_eq!(ordinal(21), "21st"); +/// assert_eq!(ordinal(22), "22nd"); +/// // Works with larger teens as well +/// assert_eq!(ordinal(112), "112th"); +/// ``` +pub fn ordinal(n: u32) -> String { + // Teens are a special case + if n % 100 >= 11 && n % 100 <= 13 { + return format!("{}th", n); + } + + let suffix = match n % 10 { + 1 => "st", + 2 => "nd", + 3 => "rd", + _ => "th", + }; + format!("{}{}", n, suffix) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ordinal() { + assert_eq!(ordinal(1), "1st"); + assert_eq!(ordinal(2), "2nd"); + assert_eq!(ordinal(3), "3rd"); + assert_eq!(ordinal(4), "4th"); + assert_eq!(ordinal(11), "11th"); + assert_eq!(ordinal(12), "12th"); + assert_eq!(ordinal(13), "13th"); + assert_eq!(ordinal(21), "21st"); + assert_eq!(ordinal(22), "22nd"); + assert_eq!(ordinal(23), "23rd"); + assert_eq!(ordinal(24), "24th"); + assert_eq!(ordinal(112), "112th"); + } +}