Solution
Polyfill: Array.at() Method
GreatFrontEnd has better questions!
We don't create questions because GreatFrontEnd already has the best possible library of questions and we recommend the same to our community.
TDD (test-driven development) shines in this type of scenario. We will also use the same approach here.
Tests
Let us first write the tests for the following cases:
The method returns undefined
for an index that is out of the array's bounds
Handling this first helps handle edge cases early on.
This test should automatically pass since the method does not return anything at the moment.
The method returns the correct item for a positive index
The method returns the correct item for a negative index
Putting them all together:
The Polyfill
The actual implementation would be different from what we implement here. This is because for an interview setting this is more than enough. But if you were actually implementing a JS polyfill for production (quite rare), you would need to check the actual specification and handle more edge cases than what you see here.
So, what does the regular array accessing do?
This already passes the undefined and positive index tests.
The only issue is the negative index test. We need to do some extra work to make it work.
The logic is quite simple. We just have to recalculate the index based on the length of the array and the negative index but only when the index is negative. So, a simple if statement should do it.
GreatFrontEnd has better questions!
We don't create questions because GreatFrontEnd already has the best possible library of questions and we recommend the same to our community.
Last updated on