Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Ockajak committed Jul 9, 2024
1 parent ddba111 commit 88aeeda
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
3 changes: 1 addition & 2 deletions src/extensions/collectible.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,9 +1125,8 @@ pub trait Collectible<Item>: IntoIterator<Item = Item> {
/// 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<Item<'a> = &'a Item>, replacement: impl IntoIterator<Item = Item>,
Expand Down
34 changes: 33 additions & 1 deletion src/extensions/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ pub trait Map<Key, Value> {
// all_unique
// includes
// subset
// replace_all

#[inline]
fn add(self, key: Key, value: Value) -> Self
Expand Down Expand Up @@ -315,6 +314,39 @@ pub trait Map<Key, Value> {
.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<Item<'a> = &'a Key>, replacement: impl IntoIterator<Item = (Key, Value)>,
) -> Self
where
Key: Eq + Hash + 'a,
Self: IntoIterator<Item = (Key, Value)> + 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<S, L, W>(
self, initial_state: S, function: impl FnMut(&mut S, (&Key, &Value)) -> Option<(L, W)>,
) -> Self::This<L, W>
Expand Down

0 comments on commit 88aeeda

Please sign in to comment.