Given two iterators of items, how can I calculate the added, kept, and removed items between the two?

Viewed 36

If I have two iterators, one representing the previous state of some collection, and one representing the current state, is there a one liner to calculate a tuple containing the items that have been added to the current state, kept between the two, and removed from the current state?

I could do this manually fairly simply, or create my own function, but I'm curious if this exists already.

Something like this: (untested)

fn delta<'a, T: PartialEq>(past: impl Iterator<Item = &'a T>, present: impl Iterator<Item = &'a T>) -> (Vec<&'a T>, Vec<&'a T>, Vec<&'a T>) {
    let past = past.collect::<Vec<_>>();
    let present = present.collect::<Vec<_>>();

    let added = present.into_iter().filter(|x| !past.contains(x)).collect::<Vec<_>>();
    let kept = present.into_iter().filter(|x| past.contains(x)).collect::<Vec<_>>();
    let removed = past.into_iter().filter(|x| !present.contains(x)).collect::<Vec<_>>();
    
    (added, kept, removed)
}

0 Answers
Related