a function to splice any stack (see the GenericStack interface).

splicing alone lets you effectively implement all sorts of array mutation methods, such as push, pop, unshift, shift, insert, rotate, and many more.

Note

the length property of your stack is not mutated/assigned by this function. you will have to do that manually yourself if your stack does not modify the length property upon the push and pop operations.

import { assertEquals } from "jsr:@std/assert"

// aliasing our functions for brevity
const
fn = spliceGenericStack,
eq = assertEquals

const my_stack = [0, 1, 2, 3, 4, 5, 6, 7]

eq(fn(my_stack, 4), [4, 5, 6, 7])
eq(my_stack, [0, 1, 2, 3])

eq(fn(my_stack, 0, 0, -3, -2, -1), [])
eq(my_stack, [-3, -2, -1, 0, 1, 2, 3])

eq(fn(my_stack, 4, 2, 0.1, 0.2, 0.3), [1, 2])
eq(my_stack, [-3, -2, -1, 0, 0.1, 0.2, 0.3, 3])

eq(fn(my_stack), [-3, -2, -1, 0, 0.1, 0.2, 0.3, 3])
eq(my_stack, [])
  • Type Parameters

    • T

    Parameters

    • stack: GenericStack<T>

      the generic stack object to splice.

    • start: number = 0

      the starting index to begin splicing from. you must provide only positive starting index values. defaults to 0.

    • OptionaldeleteCount: number

      the number of elements to remove from the start index (inclusive). if it is set to undefined, then all elements until the end of the generic stack array will be removed. defaults to undefined.

    • ...items: T[]

      insert items at the start index, so that the first inserted item will occupy the start index after the splicing.

    Returns T[]

    an array of deleted items in the generic stack will be returned.