From f272e502c4d1e2e33ab1e9fe460df69ff8f8ccd2 Mon Sep 17 00:00:00 2001 From: Scott Worley Date: Mon, 19 Aug 2024 11:09:43 -0700 Subject: [PATCH 1/1] Column counts --- src/lib.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) 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)]) + ); + } } -- 2.44.1