Build an array iterator with next(), done(), peek(), reset() and for...of support

easyAbout 20 minutesUpdated CodingProiteratorsclosuresarraysgenerators
Not solved

Share this question

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

Stuck? Take a hint

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.

Every question and answer7 days, one payment