Created
August 29, 2025 10:43
-
-
Save zekefast/5f54ea678234318a78013eafe2c8e3b2 to your computer and use it in GitHub Desktop.
Solution to the amo coding challange
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
| #[derive(Debug)] | |
| pub struct Split<'input> { | |
| // TODO: add more fields if needed, or replace/update those. | |
| input: &'input str, | |
| delimiter: char, | |
| current_position: Option<usize>, | |
| } | |
| impl<'input> Split<'input> { | |
| pub fn new(input: &'input str, delimiter: char) -> Self { | |
| Self { | |
| input, | |
| delimiter, | |
| current_position: Some(0), | |
| } | |
| } | |
| } | |
| impl<'input> Iterator for Split<'input> { | |
| type Item = &'input str; | |
| fn next(&mut self) -> Option<Self::Item> { | |
| let Some(current_position) = self.current_position else { return None; }; | |
| let input = &self.input[current_position..]; | |
| let pos = input.find(self.delimiter); | |
| let slice = &input[..pos.unwrap_or(input.len())]; | |
| self.current_position = pos.map(|p| current_position + p + 1); | |
| Some(slice) | |
| } | |
| } | |
| fn main() { | |
| let test_cases = vec![ | |
| ("multiple", "ab,cd,ef", ','), | |
| ]; | |
| for (name, input, delimiter) in test_cases { | |
| let expected = input.split(delimiter).collect::<Vec<_>>(); | |
| let result = Split::new(input, delimiter).collect::<Vec<_>>(); | |
| assert_eq!(result, expected, "test {name} failed"); | |
| } | |
| eprintln!("All tests passed!"); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It took a bit of debuging. Also I could use a boolean flag to indicate end of string instead of
Option<current_position>, but sincefindreturnsOptionit was convenient to use it.Playground to run: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=468f91121ebbd2972190082df908c5e2