Spot the bug - #6

This one is intentionally tricky.

function range(start, end) {
  return {
    [Symbol.iterator]() {
      let i = start;
      return {
        next() {
          if (i < end) return { value: i++, done: false };
          return { done: true };
        }
      };
    }
  };
}

const iter = range(1, 4)[Symbol.iterator]();
const arr = [...iter];
console.log(arr.join(','));

Reply with what is broken and how you would fix it.

Hari

Spreading iter is the bug: ... expects an iterable with iter[Symbol.iterator], but you grabbed a bare iterator that only has next, so it blows up.

Fix by spreading the iterable ([...range(1, 4)]), or add [Symbol.iterator]() { return this; } to the returned iterator so it’s self-iterable.

Sarah

Spread only works on an iterable, but range(1, 4)[Symbol.iterator]() gives you a plain iterator with just next(), so it throws.

Use [...] or Array.from on range(1, 4) directly, or make the iterator self-iterable by adding [Symbol.iterator]() { return this }.

MechaPrime