repeat_by

Function repeat_by 

Source
pub fn repeat_by<T, F>(count: usize, predicate: F) -> Vec<T>
where F: Fn(usize) -> T,
Expand description

Repeat a specified value count times by applying a predicate function to each index, returning a new vector with the generated elements.

This function takes a count and a predicate function. It applies the predicate to each index from 0 to count - 1 and collects the results into a new Vec<T>. This allows for the creation of a vector with elements generated based on their position.

Time Complexity:
O(n), where n is the number of times to repeat and generate elements.

§Arguments

  • count - The number of times to apply the predicate and generate elements.
  • predicate - A function that takes an index and returns a value of type T.

§Type Parameters

  • T - The type of elements to be generated and collected.
  • F - The type of the predicate function. Must implement the Fn(usize) -> T trait.

§Returns

  • Vec<T> - A new vector containing the elements generated by the predicate function.

§Examples

use lowdash::repeat_by;

let filled = repeat_by(5, |i| i * 2);
assert_eq!(filled, vec![0, 2, 4, 6, 8]);
use lowdash::repeat_by;

#[derive(Debug, PartialEq, Clone)]
struct Person {
    name: String,
    age: u32,
}

let filled_people = repeat_by(3, |i| Person {
    name: format!("Person {}", i + 1),
    age: 20 + i as u32 * 5,
});
assert_eq!(
    filled_people,
    vec![
        Person { name: "Person 1".to_string(), age: 20 },
        Person { name: "Person 2".to_string(), age: 25 },
        Person { name: "Person 3".to_string(), age: 30 },
    ]
);