splice

Function splice 

Source
pub fn splice<T>(collection: &[T], i: isize, elements: &[T]) -> Vec<T>
where T: Clone,
Expand description

Inserts elements into a collection at a specified index, handling negative indices and overflow. Returns a new Vec<T> with the elements inserted.

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

§Arguments

  • collection - A slice of items in which to perform the insertion.
  • i - The index at which to insert the elements. Can be negative to indicate an offset from the end.
  • elements - A slice of elements to insert.

§Type Parameters

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

§Returns

  • Vec<T> - A new vector with the specified elements inserted.

§Examples

use lowdash::splice;

let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99, 100];
let result = splice(&numbers, 2, &elements);
assert_eq!(result, vec![1, 2, 99, 100, 3, 4, 5]);
use lowdash::splice;

let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99, 100];
// Insert at the end
let result = splice(&numbers, 10, &elements);
assert_eq!(result, vec![1, 2, 3, 4, 5, 99, 100]);
use lowdash::splice;

let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99];
// Insert at negative index (-2 means len - 2 = 3)
let result = splice(&numbers, -2, &elements);
assert_eq!(result, vec![1, 2, 3, 99, 4, 5]);
use lowdash::splice;

let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99];
// Negative index beyond the start, insert at beginning
let result = splice(&numbers, -10, &elements);
assert_eq!(result, vec![99, 1, 2, 3, 4, 5]);