2619. Array Prototype Last

 

Enhancing JavaScript Arrays with a Custom last Method

As we delve deeper into JavaScript, extending the built-in prototypes can often prove invaluable for making our code cleaner and more expressive. Today, we’re focusing on a handy little method to retrieve the last element of an array with a few lines of code. For anyone interested in improving their JavaScript toolkit, this is a great example. I've also included my LeetCode solution link for further reference.

Problem Statement

We aim to extend the JavaScript Array prototype by adding a method called last. This method should return the last element of the array. If the array is empty, it should return -1.

Code Solution

javascript
Array.prototype.last = function() {
    return (this.length) ? this[this.length - 1] : -1;
};

Intuition

The purpose of this method is straightforward. In many scenarios, accessing the last element of an array is a common task. Instead of writing repetitive code to check if the array is empty and then accessing the last element, we can encapsulate this logic within a prototype method. This makes our code more concise and readable.

Approach

  1. Prototype Extension: We add the last method to Array.prototype so that it's available to all array instances.

  2. Check Length: Within the last method, we first check if the array has any elements using this.length.

  3. Return Last Element or -1: If the array is not empty, we return the last element using this[this.length - 1]. If it's empty, we return -1.

Complexity Analysis

  • Time Complexity: O(1). Accessing the length of the array and the last element (if it exists) are both constant-time operations.

  • Space Complexity: O(1). This method does not use any additional space beyond the input array.

Example Usage

Let’s see how this method works with a couple of examples:

javascript
let arr = [1, 2, 3, 4, 5];
console.log(arr.last()); // Outputs: 5

let emptyArr = [];
console.log(emptyArr.last()); // Outputs: -1

Conclusion

Extending the Array.prototype with a last method provides a neat and efficient way to handle one of the frequent tasks we encounter when working with arrays. It encapsulates the logic of checking array length and accessing the last element into a single, reusable method, improving both readability and maintainability.

For a more detailed explanation and other solutions, you can check out my Array Prototype Last - LeetCode

I hope you find this method useful in your JavaScript projects! Feel free to share your thoughts or improvements.

Happy coding!

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50