feat: ordinal utility

This commit is contained in:
Compositr 2024-12-25 22:48:55 +08:00
parent 7427427078
commit feeac0ff2d
Signed by: compositr
GPG key ID: 91E3DE20129A0B4A
2 changed files with 52 additions and 1 deletions

View file

@ -1,2 +1,3 @@
pub mod macros; pub mod macros;
pub mod time; pub mod time;
pub mod util;

50
src/util.rs Normal file
View file

@ -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");
}
}