Created
July 15, 2024 20:30
-
-
Save computermouth/6907f04cd036d487400e0cc8277e0350 to your computer and use it in GitHub Desktop.
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
const SOME: [char;10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; | |
#[derive(Debug)] | |
struct Response { | |
last: usize, | |
limit: usize, | |
payload: Vec<char> | |
} | |
impl Iterator for Response { | |
type Item = Vec<char>; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.last > SOME.len() { | |
return None; | |
} | |
*self = Builder::new(Some(self.last), Some(self.limit)).execute(); | |
Some(self.payload.clone()) | |
} | |
} | |
struct Builder { | |
last: Option<usize>, | |
limit: usize, | |
} | |
impl Builder { | |
fn new(last: Option<usize>, limit: Option<usize>) -> Builder { | |
Builder{ | |
last, | |
limit: limit.unwrap_or(3), | |
} | |
} | |
fn execute(&self) -> Response { | |
let current = match self.last { | |
None => 0, | |
Some(n) => n, | |
}; | |
let last = current + self.limit; | |
let mut out = vec![]; | |
for i in current..last { | |
if i < SOME.len() { | |
out.push(SOME[i]) | |
} | |
} | |
Response { | |
last, | |
limit: self.limit, | |
payload: out, | |
} | |
} | |
} | |
fn main(){ | |
let r = Builder::new(None, Some(1)).execute(); | |
eprintln!("r: {:?}", r); | |
for (i, r) in Builder::new(None, Some(1)).execute().enumerate() { | |
eprintln!("[{i}]: {:?}", r); | |
} | |
} | |
// OUTPUT | |
// ======================================================== | |
// r: Response { last: 1, limit: 1, payload: ['0'] } | |
// [0]: ['1'] | |
// [1]: ['2'] | |
// [2]: ['3'] | |
// [3]: ['4'] | |
// [4]: ['5'] | |
// [5]: ['6'] | |
// [6]: ['7'] | |
// [7]: ['8'] | |
// [8]: ['9'] | |
// [9]: [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment