Get Last Array Element
This challenge focuses on a fundamental array operation: retrieving the last element. Being able to efficiently access the final item in a collection is a common requirement in many programming scenarios, such as processing logs, handling user input, or iterating through data structures.
Problem Description
Your task is to create a TypeScript function that accepts an array and returns its last element.
Requirements:
- The function should be named
getLastElement. - It must accept a single argument: an array of any type.
- It should return the last element of the input array.
- If the input array is empty, the function should return
undefined.
Expected Behavior:
- For a non-empty array, the function should return the element at the highest index.
- For an empty array, the function should return
undefined.
Edge Cases:
- Empty arrays: The function must gracefully handle empty arrays.
- Arrays with a single element: The function should correctly return that element.
Examples
Example 1:
Input: [1, 2, 3, 4, 5]
Output: 5
Explanation: The last element in the array [1, 2, 3, 4, 5] is 5.
Example 2:
Input: ["apple", "banana", "cherry"]
Output: "cherry"
Explanation: The last element in the array ["apple", "banana", "cherry"] is "cherry".
Example 3:
Input: []
Output: undefined
Explanation: The input array is empty, so the function returns undefined.
Example 4:
Input: [true]
Output: true
Explanation: The array contains only one element, which is also the last element.
Constraints
- The input will always be a JavaScript/TypeScript array.
- The array elements can be of any data type (numbers, strings, booleans, objects, etc.).
- The function should have a time complexity of O(1) (constant time).
Notes
Consider how you can access the last element of an array without needing to know its length beforehand. Think about array indexing and potential pitfalls of invalid indices. You might want to leverage built-in JavaScript/TypeScript array properties or methods.