Last active
July 13, 2023 16:44
-
-
Save lffg/d4e64aa13b772c0f479450180811ac65 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::BTreeMap; | |
fn group<'a>(data: impl Iterator<Item = (&'a str, u32)>) -> BTreeMap<&'a str, u32> { | |
data.fold(BTreeMap::new(), |mut map, (date, amount)| { | |
*map.entry(date).or_default() += amount; | |
map | |
}) | |
} | |
#[test] | |
fn test() { | |
static DATA: &[(&str, u32)] = &[ | |
("2023-07-13", 12), | |
("2023-07-14", 30), | |
("2023-07-13", 4), | |
("2023-07-14", 98), | |
("2023-07-12", 4), | |
("2023-07-12", 8), | |
("2023-07-12", 31), | |
("2023-07-15", 74), | |
("2023-07-13", 12), | |
("2023-07-12", 1), | |
("2023-07-17", 3), | |
("2023-07-16", 35), | |
]; | |
assert_eq!( | |
group(DATA.iter().copied()), | |
BTreeMap::from([ | |
("2023-07-12", 44), | |
("2023-07-13", 28), | |
("2023-07-14", 128), | |
("2023-07-15", 74), | |
("2023-07-16", 35), | |
("2023-07-17", 3), | |
]) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment