Implement an array iterator
Iterator in Javascript is an object which defines a sequence and potentially a return value upon its termination.
Technically, iterators are objects which follows the iterator protocol and by having a next()
method that returns an object with two properties:
value
: The next value in the iteration sequence.done
: This is true if the last value in the sequence has already been consumed, else false.
You can learn more about iterators on MDN.
However, for our use case, we have to implement a iteratorArray
method, which takes an array as argument and returns an object with next()
and done()
properties.
Calling the next()
method should return the next item in array until the end of array, after which it returns null
and done()
methods returns a boolean flag denoting if all iterations are completed.
1. Basic Implementation
2. With startIndex implementation
A startIndex value can be passed, and iteration should start from that index.
Further Reading
I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing 🫡.