Recent Posts
Recent Comments
게으른개발너D
[Array] Array Prototype Last 본문
https://leetcode.com/problems/array-prototype-last/
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.
solution
Array.prototype.last = function() {
const length = this.length;
return length > 0 ? this[length - 1] : -1;
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
typescript
declare global {
interface Array<T> {
last(): T | -1;
}
}
Array.prototype.last = function() {
if(!this.length) return -1;
return this[this.length - 1];
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
export {};
'알고리즘 > 과제' 카테고리의 다른 글
[Array] Filter Elements from Array (filter 구현하기) (0) | 2023.07.03 |
---|---|
[Function, Closure] Function Composition (feat. reduceRight) (0) | 2023.07.03 |
[Array] Array Reduce Transformation (reduce 정의하기) (0) | 2023.07.03 |
[Promise] Sleep ⭐️ (0) | 2023.07.03 |
[Function, Closure] Counter ⭐️ (0) | 2023.07.03 |
Comments