count_by

Function count_by 

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

Counts the number of elements in a collection that satisfy a given predicate.

This function iterates over a slice of items and applies the provided predicate to each item. It returns the total count of items for which the predicate returns true.

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

§Arguments

  • collection - A slice of items to be evaluated.
  • predicate - A function that takes a reference to an item and returns a boolean. If the predicate returns true, the item is counted.

§Type Parameters

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

§Returns

  • usize - The number of elements in the collection that satisfy the predicate.

§Examples

use lowdash::count_by;

let numbers = vec![1, 2, 3, 4, 5];
// Count even numbers
let result = count_by(&numbers, |&x| x % 2 == 0);
assert_eq!(result, 2);
use lowdash::count_by;

#[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 },
    Person { name: "Dave".to_string(), age: 30 },
];

// Count people who are at least 30 years old
let count_adults = count_by(&people, |p| p.age >= 30);
assert_eq!(count_adults, 3);