Retrieve the Last Element of an Array in TypeScript
This challenge focuses on a fundamental array operation: extracting the last element. It's a common task in programming, useful for processing data, iterating through collections, and more. Your task is to write a TypeScript function that efficiently and safely retrieves the last element of an array.
Problem Description
You are required to implement a TypeScript function named getLastElement that takes an array as input and returns its last element. The function should handle various scenarios, including empty arrays and arrays of different data types.
Key Requirements:
- The function must accept an array of any type as input (e.g.,
number[],string[],any[]). - The function must return the last element of the array.
- If the input array is empty, the function should return
undefined. This is crucial for preventing errors and handling edge cases gracefully. - The function should be type-safe, leveraging TypeScript's type system to ensure correct usage and prevent unexpected behavior.
Expected Behavior:
The function should accurately return the last element of the array without modifying the original array. It should be robust enough to handle arrays containing various data types.
Edge Cases to Consider:
- Empty Array: The most important edge case is when the input array is empty. Returning
undefinedis the expected behavior in this scenario. - Array with a Single Element: The function should correctly return the single element when the array contains only one element.
- Arrays of Different Data Types: The function should work correctly with arrays containing numbers, strings, booleans, objects, or any combination of these.
Examples
Example 1:
Input: [1, 2, 3, 4, 5]
Output: 5
Explanation: The last element of the array [1, 2, 3, 4, 5] is 5.
Example 2:
Input: ["apple", "banana", "cherry"]
Output: "cherry"
Explanation: The last element of 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 true.
Constraints
- The input array can contain any data type.
- The function must return
undefinedif the array is empty. - The function should have a time complexity of O(1) – accessing the last element should be a constant-time operation.
- The function should not modify the original array.
Notes
Consider using the length property of the array to determine the index of the last element. Remember to handle the edge case of an empty array to avoid errors. TypeScript's type system can be used to ensure type safety and provide better code completion and error checking. Focus on writing clean, readable, and efficient code.