|
| 1 | +use chrono::{ParseWeekdayError, Weekday}; |
| 2 | + |
| 3 | +const WEEKDAY_CONVERSION_MAP: [(&str, &str); 3] = |
| 4 | + [("tues", "tue"), ("thurs", "thu"), ("thus", "thu")]; |
| 5 | + |
| 6 | +pub(crate) fn parse_weekday(s: &str) -> Result<Weekday, ParseWeekdayError> { |
| 7 | + let mut s = s.trim().to_lowercase(); |
| 8 | + for (before, after) in WEEKDAY_CONVERSION_MAP { |
| 9 | + if s == before { |
| 10 | + s = String::from(after); |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | + s.trim().parse::<Weekday>() |
| 15 | +} |
| 16 | + |
| 17 | +#[cfg(test)] |
| 18 | +mod tests { |
| 19 | + |
| 20 | + use chrono::Weekday::*; |
| 21 | + |
| 22 | + use crate::parse_weekday::parse_weekday; |
| 23 | + #[test] |
| 24 | + fn test_valid_weekdays() { |
| 25 | + let days = [ |
| 26 | + ("mon", Mon), |
| 27 | + ("monday", Mon), |
| 28 | + ("tue", Tue), |
| 29 | + ("tues", Tue), |
| 30 | + ("tuesday", Tue), |
| 31 | + ("wed", Wed), |
| 32 | + ("wednesday", Wed), |
| 33 | + ("thu", Thu), |
| 34 | + ("thursday", Thu), |
| 35 | + ("fri", Fri), |
| 36 | + ("friday", Fri), |
| 37 | + ("sat", Sat), |
| 38 | + ("saturday", Sat), |
| 39 | + ("sun", Sun), |
| 40 | + ("sunday", Sun), |
| 41 | + ]; |
| 42 | + |
| 43 | + for day in days.iter() { |
| 44 | + let mut test_strings = vec![]; |
| 45 | + test_strings.push(String::from(day.0)); |
| 46 | + test_strings.push(format!(" {}", day.0)); |
| 47 | + test_strings.push(format!(" {} ", day.0)); |
| 48 | + test_strings.push(format!("{} ", day.0)); |
| 49 | + test_strings.push(format!(" {}", day.0.to_uppercase())); |
| 50 | + |
| 51 | + let (left, right) = day.0.split_at(1); |
| 52 | + test_strings.push(format!("{}{}", left.to_uppercase(), right.to_lowercase())); |
| 53 | + test_strings.push(format!("{}{}", left.to_lowercase(), right.to_uppercase())); |
| 54 | + |
| 55 | + for str in test_strings.iter() { |
| 56 | + assert!(parse_weekday(str).is_ok()); |
| 57 | + assert_eq!(parse_weekday(str).unwrap(), day.1); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_invalid_weekdays() { |
| 64 | + let days = [ |
| 65 | + "mond", |
| 66 | + "tuesda", |
| 67 | + "we", |
| 68 | + "th", |
| 69 | + "fr", |
| 70 | + "sa", |
| 71 | + "su", |
| 72 | + "garbageday", |
| 73 | + "tomorrow", |
| 74 | + "yesterday", |
| 75 | + ]; |
| 76 | + for day in days { |
| 77 | + assert!(parse_weekday(day).is_err()); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments