From: Scott Worley Date: Mon, 19 Aug 2024 18:09:43 +0000 (-0700) Subject: Column counts X-Git-Tag: v0.2.0~16 X-Git-Url: http://git.scottworley.com/tablify/commitdiff_plain/f272e502c4d1e2e33ab1e9fe460df69ff8f8ccd2?hp=8110b492cfa41fd99bfb639d7491b4e075fa9385 Column counts --- diff --git a/src/lib.rs b/src/lib.rs index 56a2b6d..e90f66b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,6 @@ #[cfg(test)] +use std::collections::HashMap; +#[cfg(test)] use std::io::BufRead; #[cfg(test)] use std::iter::Iterator; @@ -66,6 +68,19 @@ fn read_rows(input: impl std::io::Read) -> impl Iterator HashMap { + rows.iter() + .flat_map(|r| r.entries.iter()) + .fold(HashMap::new(), |mut counts, e| { + counts + .entry(String::from(e)) + .and_modify(|c| *c += 1) + .or_insert(1); + counts + }) +} + pub fn tablify(_input: &impl std::io::Read) -> String { String::from("Hello, world!") } @@ -167,4 +182,24 @@ mod tests { assert!(bad2.is_err()); assert!(format!("{bad2:?}").contains("3: Entry with no header")); } + + #[test] + fn test_column_counts() { + assert_eq!( + column_counts( + &read_rows(&b"foo\n bar\n baz\n"[..]) + .collect::, _>>() + .unwrap() + ), + HashMap::from([(String::from("bar"), 1), (String::from("baz"), 1)]) + ); + assert_eq!( + column_counts( + &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]) + .collect::, _>>() + .unwrap() + ), + HashMap::from([(String::from("bar"), 1), (String::from("baz"), 2)]) + ); + } }