pub fn partition_by<T, K, F>(collection: &[T], iteratee: F) -> Vec<Vec<T>>Expand description
Divide a collection into partitions based on a key extracted by a provided function, preserving the order of elements and the order of partitions as they first appear.
This function takes a slice of items and splits it into multiple partitions. Each partition
contains elements that share the same key, as determined by the iteratee function.
The order of partitions corresponds to the order in which their keys first appear in the collection.
Time Complexity:
O(n), where n is the number of elements in the collection.
§Arguments
collection- A slice of items to be partitioned.iteratee- A function that takes a reference to an item and returns a key of typeK.
§Type Parameters
T- The type of elements in the collection. Must implementClone.K- The type of the key extracted from each element used to determine partitions. Must implementHash,Eq, andClone.F- The type of the iteratee function. Must implementFn(&T) -> K.
§Returns
Vec<Vec<T>>- A vector of partitions, where each partition is a vector of elements sharing the same key.
§Examples
use lowdash::partition_by;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let partitions = partition_by(&numbers, |x| *x);
assert_eq!(
partitions,
vec![vec![1], vec![2, 2], vec![3, 3], vec![4], vec![5]]
);use lowdash::partition_by;
#[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: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let partitions = partition_by(&people, |p| p.age);
assert_eq!(
partitions,
vec![
vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Alice".to_string(), age: 25 },
],
vec![
Person { name: "Bob".to_string(), age: 30 },
],
vec![
Person { name: "Carol".to_string(), age: 35 },
],
]
);