slight refactor of numeric suffixes with test

This commit is contained in:
Mike Cugini 2021-03-17 17:13:24 -04:00
parent ded927418b
commit 1fb0b63bcc

View File

@ -102,6 +102,34 @@ impl Iterator for AlphabeticSuffixGenerator {
} }
} }
struct NumericSuffixGenerator {
current: usize,
last: usize,
}
impl NumericSuffixGenerator {
fn new(start: usize, count: usize) -> NumericSuffixGenerator {
NumericSuffixGenerator {
current: start,
last: (start + count),
}
}
}
impl Iterator for NumericSuffixGenerator {
type Item = String;
fn next(&mut self) -> Option<String> {
if self.current == self.last {
return None;
}
let next = self.current.to_string();
self.current += 1;
Some(next)
}
}
fn try_main() -> Result<(), Box<dyn Error>> { fn try_main() -> Result<(), Box<dyn Error>> {
let opts: Options = argh::from_env(); let opts: Options = argh::from_env();
@ -129,7 +157,7 @@ fn try_main() -> Result<(), Box<dyn Error>> {
Some(num) => num, Some(num) => num,
None => 0, None => 0,
}; };
Box::new((numeric_start..(numeric_start + opts.count)).map(|num| format!("{}", num))) Box::new(NumericSuffixGenerator::new(numeric_start, opts.count))
} else { } else {
Box::new(AlphabeticSuffixGenerator::new(opts.count)) Box::new(AlphabeticSuffixGenerator::new(opts.count))
}; };
@ -182,6 +210,18 @@ fn main() {
mod test { mod test {
use super::*; use super::*;
#[test]
fn test_numeric_suffix_generator_output() {
// tuple of start, count
let testcases = vec![(0, 10), (5, 20), (0, 200), (10, 5)];
for (start, count) in testcases {
let expected: Vec<String> = (start..(start + count)).map(|i| i.to_string()).collect();
let actual: Vec<String> = NumericSuffixGenerator::new(start, count).collect();
assert_eq!(actual, expected)
}
}
#[test] #[test]
fn test_alpha_suffix_generator_min_digits() { fn test_alpha_suffix_generator_min_digits() {
// tuple of count => expected min length of suffix // tuple of count => expected min length of suffix