From 1fb0b63bcc81626528600ca1261eb9473292faa3 Mon Sep 17 00:00:00 2001 From: Mike Cugini Date: Wed, 17 Mar 2021 17:13:24 -0400 Subject: [PATCH] slight refactor of numeric suffixes with test --- src/main.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index cc09bb7..981c0a7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 { + if self.current == self.last { + return None; + } + + let next = self.current.to_string(); + self.current += 1; + Some(next) + } +} + fn try_main() -> Result<(), Box> { let opts: Options = argh::from_env(); @@ -129,7 +157,7 @@ fn try_main() -> Result<(), Box> { Some(num) => num, None => 0, }; - Box::new((numeric_start..(numeric_start + opts.count)).map(|num| format!("{}", num))) + Box::new(NumericSuffixGenerator::new(numeric_start, opts.count)) } else { Box::new(AlphabeticSuffixGenerator::new(opts.count)) }; @@ -182,6 +210,18 @@ fn main() { mod test { 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 = (start..(start + count)).map(|i| i.to_string()).collect(); + let actual: Vec = NumericSuffixGenerator::new(start, count).collect(); + assert_eq!(actual, expected) + } + } + #[test] fn test_alpha_suffix_generator_min_digits() { // tuple of count => expected min length of suffix