diff --git a/src/extensions/collectible.rs b/src/extensions/collectible.rs index ef39aac..c1b0e14 100644 --- a/src/extensions/collectible.rs +++ b/src/extensions/collectible.rs @@ -1125,9 +1125,8 @@ pub trait Collectible: IntoIterator { /// use cantrip::*; /// /// let a = vec![1, 2, 3, 3]; - /// let b = vec![2, 3]; /// - /// assert_eq!(a.replace_all(&b, vec![4, 5]), vec![1, 4, 5, 3]); + /// assert_eq!(a.replace_all(&vec![2, 3], vec![4, 5]), vec![1, 4, 5, 3]); /// ``` fn replace_all<'a>( self, elements: &'a impl Iterable = &'a Item>, replacement: impl IntoIterator, diff --git a/src/extensions/map.rs b/src/extensions/map.rs index 14686d0..41116d8 100644 --- a/src/extensions/map.rs +++ b/src/extensions/map.rs @@ -26,7 +26,6 @@ pub trait Map { // all_unique // includes // subset - // replace_all #[inline] fn add(self, key: Key, value: Value) -> Self @@ -315,6 +314,39 @@ pub trait Map { .collect() } + /// Creates a map from the original map by replacing the given occurrences of elements + /// found in another collection with elements of a replacement collection. + /// + /// # Example + /// + /// ``` + /// use cantrip::*; + /// use std::collections::HashMap; + /// + /// let a = HashMap::from([ + /// (1, "a"), + /// (2, "b"), + /// (3, "c"), + /// ]); + /// + /// assert_eq!(a.replace_all(&vec![2, 3], vec![(4, "d"), (5, "e")]),HashMap::from([ + /// (1, "a"), + /// (4, "d"), + /// (5, "e"), + /// ])); + /// ``` + fn replace_all<'a>( + self, elements: &'a impl Iterable = &'a Key>, replacement: impl IntoIterator, + ) -> Self + where + Key: Eq + Hash + 'a, + Self: IntoIterator + FromIterator<(Key, Value)>, + { + let iterator = elements.iterator(); + let removed: HashSet<&Key> = HashSet::from_iter(iterator); + self.into_iter().filter(|x| !removed.contains(&x.0)).chain(replacement).collect() + } + fn scan( self, initial_state: S, function: impl FnMut(&mut S, (&Key, &Value)) -> Option<(L, W)>, ) -> Self::This