filter_reject

Function filter_reject 

Source
pub fn filter_reject<T, F>(collection: &[T], predicate: F) -> (Vec<T>, Vec<T>)
where T: Clone, F: Fn(&T, usize) -> bool,
Expand description

Filters a collection into two separate vectors based on a predicate function.

This function iterates over a slice of items, applies the provided predicate to each item along with its index, and separates the items into two vectors:

  • kept: Contains items for which the predicate returned true.
  • rejected: Contains items for which the predicate returned false.

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

§Arguments

  • collection - A slice of items to be filtered.
  • predicate - A function that takes a reference to an item and its index, returning a boolean. If the predicate returns true, the item is kept; otherwise, it is rejected.

§Type Parameters

  • T - The type of elements in the input collection. Must implement Clone.
  • F - The type of the predicate function.

§Returns

  • (Vec<T>, Vec<T>) - A tuple containing two vectors:
    • The first vector (kept) contains all items for which the predicate returned true.
    • The second vector (rejected) contains all items for which the predicate returned false.

§Examples

use lowdash::filter_reject;

let numbers = vec![1, 2, 3, 4, 5];
// Separate even and odd numbers
let (evens, odds) = filter_reject(&numbers, |&x, _| x % 2 == 0);
assert_eq!(evens, vec![2, 4]);
assert_eq!(odds, vec![1, 3, 5]);
use lowdash::filter_reject;

#[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: "Carol".to_string(), age: 35 },
];

// Separate people who are at least 30 years old
let (adults, juniors) = filter_reject(&people, |person, _| person.age >= 30);
assert_eq!(adults, vec![
    Person { name: "Bob".to_string(), age: 30 },
    Person { name: "Carol".to_string(), age: 35 },
]);
assert_eq!(juniors, vec![
    Person { name: "Alice".to_string(), age: 25 },
]);