Skip to content

count_by

Counts the elements of items per key returned by key.

use helpers4::array::count_by;

Cargo feature array (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features array

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.5", default-features = false, features = ["array"] }
pub fn count_by<T, K: Eq + Hash>(items: &[T], mut key: impl FnMut(&T) -> K) -> HashMap<K, usize>
ParameterTypeDescription
items&[T]The elements to count.
keyimpl FnMut(&T) -> KReturns the key to count each element under.

HashMap<K, usize>

use helpers4::array::count_by;

let counts = count_by(&[1, 2, 3, 4, 5], |n| if n % 2 == 0 { "even" } else { "odd" });
assert_eq!(counts["odd"], 3);
assert_eq!(counts["even"], 2);

src/array/count_by.rs