Build an array iterator with next(), done(), peek(), reset() and for...of support
Problem
Interviewers often open with a small helper that walks an array one item at a time, then ask how it relates to JavaScript's own iterators. Implement createIterator(array). It returns an object with these methods:
const it = createIterator(["a", "b", "c"]);
it.next(); // "a"
it.peek(); // "b"
it.done(); // false
[...it]; // ["b", "c"] (spreading does not move the iterator)
it.next(); // "b"
it.next(); // "c"
it.done(); // true
it.next(); // undefined
it.reset();
it.next(); // "a"Ref. UR-1466 · © UIRound · uiround.com/questions/build-an-array-iterator-with-next-done-peek-and-reset-that-also-works-with-for-of
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 6
- edge cases
- 4
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1The iterator only needs one piece of state: the index of the next item. Which methods move it, and which only read it?
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.