chunk

Function chunk 

Source
pub fn chunk<T>(collection: &[T], size: usize) -> Vec<Vec<T>>
where T: Clone,
Expand description

Divide a collection into smaller chunks of a specified size, preserving the order of elements.

This function takes a slice of items and splits it into multiple chunks, each with a maximum of size elements. The order of elements is preserved, and the last chunk may contain fewer elements if the total number of elements is not perfectly divisible by size.

Panics:
Panics if size is less than or equal to 0.

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

§Arguments

  • collection - A slice of items to be divided into chunks.
  • size - The maximum number of elements each chunk should contain.

§Type Parameters

  • T - The type of elements in the collection. Must implement Clone.

§Returns

  • Vec<Vec<T>> - A vector of chunks, where each chunk is a vector of elements.

§Examples

use lowdash::chunk;

let numbers = vec![1, 2, 3, 4, 5, 6, 7];
let chunks = chunk(&numbers, 3);
assert_eq!(
    chunks,
    vec![vec![1, 2, 3], vec![4, 5, 6], vec![7]]
);
use lowdash::chunk;

#[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: "Carol".to_string(), age: 35 },
    Person { name: "Dave".to_string(), age: 40 },
];

let chunks = chunk(&people, 2);
assert_eq!(
    chunks,
    vec![
        vec![
            Person { name: "Alice".to_string(), age: 25 },
            Person { name: "Bob".to_string(), age: 30 },
        ],
        vec![
            Person { name: "Carol".to_string(), age: 35 },
            Person { name: "Dave".to_string(), age: 40 },
        ],
    ]
);