Topic Description

Please implement Array.prototype.at, a method that accepts an integer as input and retrieves the corresponding element from the array. Besides positive integers, it should also handle negative integers, with negative integers counting from the end of the array. Here are some usage examples:

const arr = ["Explain", "This"];
console.log(arr.at(0)); // Explain
console.log(arr.at(1)); // This
console.log(arr.at(2)); // undefined

console.log(arr.at(-1)); // This
console.log(arr.at(-2)); // Explain
console.log(arr.at(-3)); // undefined

Answer

Array.prototype.at = function(index){
	const idx = index < 0 ? index + this.length : index
	return this[idx]
}