Created
November 12, 2024 05:24
-
-
Save Soumyarian98/ca52da61309d1c6ebe676fd5dde27603 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| declare global { | |
| interface Array<T> { | |
| atIndex(index: number): T | undefined; | |
| } | |
| } | |
| Array.prototype.atIndex = function <T>(index: number): T | undefined { | |
| if (index < 0) { | |
| index = this.length + index; // Convert negative index to positive | |
| } | |
| return this[index]; | |
| }; | |
| // Usage example: | |
| const arr = [10, 20, 30, 40, 50]; | |
| console.log(arr.atIndex(-1)); // Outputs: 50 | |
| console.log(arr.atIndex(-2)); // Outputs: 40 | |
| console.log(arr.atIndex(0)); // Outputs: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment