Function replace

Source
pub fn replace<T>(collection: &[T], old: T, new: T, n: usize) -> Vec<T>
where T: PartialEq + Clone,
Expand description

Replaces occurrences of a specified value in a collection with a new value, up to a maximum number of replacements.

This function iterates over a slice of items, replacing each occurrence of old with new until n replacements have been made. If n is zero, no replacements are performed. The function preserves the order of elements and does not modify the original collection.

Time Complexity: O(n), where n is the number of elements in the collection.

§Arguments

  • collection - A slice of items in which to perform replacements.
  • old - The value to be replaced.
  • new - The value to replace with.
  • n - The maximum number of replacements to perform. If n is zero, no replacements are done.

§Type Parameters

  • T - The type of elements in the collection. Must implement PartialEq and Clone.

§Returns

  • Vec<T> - A new vector with the specified replacements made.

§Examples

use lowdash::replace;

let numbers = vec![1, 2, 2, 3, 4, 2, 5];
let result = replace(&numbers, 2, 9, 2);
assert_eq!(result, vec![1, 9, 9, 3, 4, 2, 5]);
use lowdash::replace;

#[derive(Debug, PartialEq, Clone)]
struct Person {
    name: String,
    age: u32,
}

let people = vec![
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Bob".to_string(), age: 30 },
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Carol".to_string(), age: 35 },
];

let new_person = Person { name: "Dave".to_string(), age: 40 };
let result = replace(&people, people[0].clone(), new_person.clone(), 1);
assert_eq!(result, vec![new_person, people[1].clone(), people[2].clone(), people[3].clone()]);