Array Prototype Last Problem
#2619
Description
LeetCode Problem 2619.
Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.
You may assume the array is the output of JSON.parse.
Example 1:
Input: nums = [null, {}, 3]
Output: 3
Explanation: Calling nums.last() should return the last element: 3.
Example 2:
Input: nums = []
Output: -1
Explanation: Because there are no elements, return -1.
Constraints:
arris a valid JSON array0 <= arr.length <= 1000
Solution
Approach: Extend Array.prototype
Methods shared by all arrays live on Array.prototype, so assigning a function there makes last() available on every array.
- Inside a normal
function(not an arrow function),thisis the array the method was called on. - An empty array returns
-1; otherwise return the element at indexthis.length - 1.
Check the length rather than testing the value itself: the last element may legitimately be null, 0 or {}, and the empty check must not confuse those with "no element".
In TypeScript the method also has to be declared on the Array interface so the compiler accepts arr.last().
Complexity: time O(1), space O(1).
Array.prototype.last = function () {
return this.length === 0 ? -1 : this[this.length - 1];
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/