associate

Function associate 

Source
pub fn associate<T, K, V, F>(collection: &[T], transform: F) -> HashMap<K, V>
where K: Eq + Hash, F: Fn(&T) -> (K, V),
Expand description

Creates a HashMap by transforming each element in a collection into a key-value pair using a provided function.

This function takes a slice of items and a transform function, then returns a new HashMap<K, V> where each key-value pair is generated by applying the transform function to an element in the collection. If multiple elements produce the same key, the last occurrence will overwrite previous ones.

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

§Arguments

  • collection - A slice of items to be transformed into key-value pairs.
  • transform - A function that takes an item from the collection and returns a key-value pair.

§Type Parameters

  • T - The type of elements in the collection.
  • K - The type of keys in the resulting HashMap. Must implement Eq and Hash.
  • V - The type of values in the resulting HashMap.
  • F - The type of the transform function. Must implement Fn(&T) -> (K, V).

§Returns

  • HashMap<K, V> - A HashMap where each key-value pair is the result of applying the transform function to an element in the collection.

§Examples

use lowdash::associate;
use std::collections::HashMap;

let numbers = vec![1, 2, 3, 4, 5];
let map = associate(&numbers, |&x| (x, x * x));
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 4);
expected.insert(3, 9);
expected.insert(4, 16);
expected.insert(5, 25);
assert_eq!(map, expected);
use lowdash::associate;
use std::collections::HashMap;

#[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: "Charlie".to_string(), age: 35 },
];

let map = associate(&people, |person| (person.name.clone(), person.age));
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), 25);
expected.insert("Bob".to_string(), 30);
expected.insert("Charlie".to_string(), 35);
assert_eq!(map, expected);
use lowdash::associate;
use std::collections::HashMap;

let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = associate(&strings, |s| (s.chars().next().unwrap(), s.len()));
let mut expected = HashMap::new();
expected.insert('a', 7); // "apricot" has 7 characters
expected.insert('b', 9); // "blueberry" has 9 characters
assert_eq!(map, expected);