Skip to content

Instantly share code, notes, and snippets.

@Soumyarian98
Created November 12, 2024 05:24
Show Gist options
  • Select an option

  • Save Soumyarian98/ca52da61309d1c6ebe676fd5dde27603 to your computer and use it in GitHub Desktop.

Select an option

Save Soumyarian98/ca52da61309d1c6ebe676fd5dde27603 to your computer and use it in GitHub Desktop.
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