Last active
November 3, 2023 11:35
-
-
Save matthewjberger/ed852aaea2620078cbf8ca3e56d2c5a9 to your computer and use it in GitHub Desktop.
Does a string contain a single number within a range in rust - https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=837dee8a23be886210a55207672c9659
This file contains hidden or 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 contains_single_num_in_range(s: &str, section_index: usize, min: u8, max: u8) -> Option<u8> { | |
s.split('/') | |
.nth(section_index)? | |
.split('-') | |
.filter_map(|part| part.parse::<u8>().ok()) | |
.find(|&num| (min..=max).contains(&num)) | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_contains_single_num_in_first_section() { | |
let input = "lift-8/state/op/report"; | |
let section_index = 0; | |
let min = 1; | |
let max = 8; | |
assert_eq!( | |
contains_single_num_in_range(input, section_index, min, max), | |
Some(8) | |
); | |
} | |
#[test] | |
fn test_contains_single_num_in_second_section() { | |
let input = "lift/state-7/op/report"; | |
let section_index = 1; | |
let min = 1; | |
let max = 8; | |
assert_eq!( | |
contains_single_num_in_range(input, section_index, min, max), | |
Some(7) | |
); | |
} | |
#[test] | |
fn test_contains_no_num_in_range() { | |
let input = "lift-9/state/op/report"; | |
let section_index = 0; | |
let min = 1; | |
let max = 8; | |
assert_eq!( | |
contains_single_num_in_range(input, section_index, min, max), | |
None | |
); | |
} | |
#[test] | |
fn test_contains_no_num() { | |
let input = "lift-/state/op/report"; | |
let section_index = 0; | |
let min = 1; | |
let max = 8; | |
assert_eq!( | |
contains_single_num_in_range(input, section_index, min, max), | |
None | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment