I've run across a codewars exercise which I'm struggling with: https://www.codewars.com/kata/scraping-codewars-top-500-users/train/javascript
I want to be able to access an array as if was 1-indexed, instead of 0-indexed.
For example, if I have this array:
let a = [1, 2, 3, 4, 5]
I would like to do a[5]
and get 5
as a result (instead of 4
).
So far, I've come up with this:
Array.prototype.get = function(i, fallback) {
return this[i-1] || fallback;
}
And with:
class BaseOneArray extends Array {
constructor(...args) {
super(...args);
}
get(i, fallback) {
return this[i-1];
}
}
However, both of these approaches only work when accessing the array like this: a.get(4)
but not when doing it like this: a[4]
How could I make the []
operators from an array work as if the array had a 1-based index?
The array must have the same number of items, so I can't just add a fill value in the first position to move all the elements one place up.