Boundary-Safe Array Access

Difficulty: Easy · Topics: Array, Edge Cases, Utility

Difficulty: Easy  |  Tags: Array, Edge Cases, Utility

Description

Implement utility functions for safely accessing array elements that handle all edge cases gracefully instead of throwing index-out-of-bounds exceptions.

Implement:

safeGet(array, index, defaultValue) → T
safeFirst(array, defaultValue) → T
safeLast(array, defaultValue) → T
safeSlice(array, from, to) → T[]

Examples

Example 1 — safeGet:

Input:  arr = [10, 20, 30], index = 5, default = -1
Output: -1

Example 2 — Negative index:

Input:  arr = [10, 20, 30], index = -1, default = 0
Output: 30
Explanation: Negative indices count from the end (like Python).

Example 3 — safeFirst on empty:

Input:  arr = [], default = "none"
Output: "none"

Example 4 — safeSlice out of bounds:

Input:  arr = [1, 2, 3], from = 1, to = 100
Output: [2, 3]
Explanation: Clamp `to` to array length.

Example 5 — null array:

Input:  arr = null, index = 0, default = 42
Output: 42

Constraints

Practice this problem

Related problems