filter_map

Function filter_map 

Source
pub fn filter_map<T, R, F>(collection: &[T], callback: F) -> Vec<R>
where F: Fn(&T, usize) -> (R, bool),
Expand description

Apply a function to each item in a collection, filtering and transforming items based on a callback.

This function iterates over a collection and applies the provided callback function to each item along with its index. If the callback returns (R, true), the transformed value R is included in the resulting vector.

§Arguments

  • collection - A slice of items.
  • callback - A function that takes a reference to an item and its index, returning a tuple (R, bool) where R is the transformed value and bool indicates whether to include it.

§Returns

  • Vec<R> - A vector containing the transformed items that passed the callback’s predicate.

§Examples

use lowdash::filter_map;
let numbers = vec![1, 2, 3, 4, 5];
// Double even numbers
let result = filter_map(&numbers, |x, _| {
    if *x % 2 == 0 {
        (x * 2, true)
    } else {
        (0, false)
    }
});
assert_eq!(result, vec![4, 8]);
use lowdash::filter_map;

#[derive(Debug, PartialEq)]
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 },
];

// Extract names of people older than 28
let names: Vec<String> = filter_map(&people, |p, _| {
    if p.age > 28 {
        (p.name.clone(), true)
    } else {
        (String::new(), false)
    }
});
assert_eq!(names, vec!["Bob".to_string(), "Carol".to_string()]);