generated from Astrial.org/template
feat: ordinal utility
This commit is contained in:
parent
7427427078
commit
feeac0ff2d
2 changed files with 52 additions and 1 deletions
|
@ -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
50
src/util.rs
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue