count_values_by

Function count_values_by 

Source
pub fn count_values_by<T, U, F>(
    collection: &[T],
    mapper: F,
) -> HashMap<U, usize>
where U: Hash + Eq + Clone, F: Fn(&T) -> U,
Expand description

Counts the number of occurrences of each value in a collection after applying a mapper function.

This function iterates over a slice of items, applies the mapper function to each item, and returns a HashMap where each key is the mapped value, and the corresponding value is the number of times that mapped value appears.

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

§Arguments

  • collection - A slice of items to be counted.
  • mapper - A function that maps an item of type T to a key of type U.

§Type Parameters

  • T - The type of elements in the input collection.
  • U - The type of keys in the resulting HashMap. Must implement Hash, Eq, and Clone.

§Returns

  • HashMap<U, usize> - A map where keys are the mapped values from the collection and values are their counts.

§Examples

use lowdash::count_values_by;
use std::collections::HashMap;

let chars = vec!['a', 'b', 'a', 'c', 'b', 'd'];
let result = count_values_by(&chars, |x| x.clone());
let mut expected = HashMap::new();
expected.insert('a', 2);
expected.insert('b', 2);
expected.insert('c', 1);
expected.insert('d', 1);
assert_eq!(result, expected);
use lowdash::count_values_by;
use std::collections::HashMap;

 let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let result = count_values_by(&numbers, |x| *x);
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 2);
expected.insert(3, 2);
expected.insert(4, 1);
expected.insert(5, 1);
assert_eq!(result, expected);