]> git.scottworley.com Git - tablify/blobdiff - src/lib.rs
Column counts
[tablify] / src / lib.rs
index 56a2b6ddec94a404a23d582bbf3b16fcc06bb5bc..e90f66b37f2359542bad445064f86ea1ee2ec6ad 100644 (file)
@@ -1,4 +1,6 @@
 #[cfg(test)]
 #[cfg(test)]
+use std::collections::HashMap;
+#[cfg(test)]
 use std::io::BufRead;
 #[cfg(test)]
 use std::iter::Iterator;
 use std::io::BufRead;
 #[cfg(test)]
 use std::iter::Iterator;
@@ -66,6 +68,19 @@ fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput,
     Reader::new(std::io::BufReader::new(input).lines())
 }
 
     Reader::new(std::io::BufReader::new(input).lines())
 }
 
+#[cfg(test)]
+fn column_counts(rows: &[RowInput]) -> HashMap<String, usize> {
+    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!")
 }
 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"));
     }
         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::<Result<Vec<_>, _>>()
+                    .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::<Result<Vec<_>, _>>()
+                    .unwrap()
+            ),
+            HashMap::from([(String::from("bar"), 1), (String::from("baz"), 2)])
+        );
+    }
 }
 }