Spot the bug - #20

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.

WaffleFries

What’s broken is iter isn’t iterable. You grabbed the iterator object ({ next() { … } }), but it doesn’t have a [Symbol. iterator]() method, so [. . . iter] blows up. Fix is either spread the iterable: const arr = [. . . range(1, 4)]; or make the iterator return itself:

const iter = range(1, 4)[Symbol.iterator]();
iter[Symbol.iterator] = () => iter;
const arr = [...iter];

I found a related kirupa. com article that can help you go deeper into this topic: