slice_to_map

Function slice_to_map 

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

Transforms a slice of items into a HashMap by applying a provided function to each item.

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::slice_to_map;
use std::collections::HashMap;

let numbers = vec![1, 2, 3, 4, 5];
let map = slice_to_map(&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::slice_to_map;
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 = slice_to_map(&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::slice_to_map;
use std::collections::HashMap;

let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = slice_to_map(&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);