Magician In Training: Incorrect Expectation in `testInsertAtOfEmptyStack`

Incorrect Expectation in testInsertAtOfEmptyStack

Summary

The testInsertAtOfEmptyStack test case contains an incorrect expectation based on the documented behavior of insert(_:at:from:).

Source Implementation

func insert(_ newCard: Int, at index: Int, from stack: [Int]) -> [Int] {
  var newStack = stack
  
  if newStack.indices.contains(index) {
    newStack.insert(newCard, at: index)
  }
  
  return newStack
}

Current Test

func testInsertAtOfEmptyStack() {
    let stack = [Int]()
    #expect(insert(5, at: 0, from: stack) == [5])
}

Problem

For an empty array:

array.indices.contains(0)

evaluates to:

false

Since the condition fails, the function does not insert the element and instead returns the original array unchanged.

This behavior is consistent with the documented requirements:

If the given index is not a valid index in the stack, the original stack should be returned, unchanged.

Because an empty array has no valid indices, index 0 is considered invalid under the current implementation.

Expected Behavior

The test should reflect the actual contract and implementation behavior by expecting the original empty array to be returned unchanged.

Proposed Fix

Replace:

func testInsertAtOfEmptyStack() {
    let stack = [Int]()
    #expect(insert(5, at: 0, from: stack) == [5])
}

With:

func testInsertAtOfEmptyStack() {
    let stack = [Int]()
    #expect(insert(5, at: 0, from: stack) == [])
}

Additional Notes

If insertion into an empty array at index 0 is intended to be valid behavior, then the implementation itself should be changed instead of the test. The current implementation explicitly rejects insertion when the index is not contained within array.indices.