A while back I was creating a
URLPattern class that allows you to match a URL
Pattern to a URL. I allowed
', ' to act as an and operator (
&&). In that way,
my class was the following structure:
I wanted someone to be able to do
[...pattern] and get back:
That is when I came across the
From the MDN docs:
Symbol.iteratorsymbol specifies the default iterator for an object. Used by
Symbol.iterator is a property of the builtin
Symbol object that exists
as a property on the
Set prototype, and many other builtin iterators.
It gets called whenever the
... (spread syntax) or
Array.from is run on the
Symbol.iterator inside classes, define a method with the method name being
[Symbol.iterator]. Here is an example usage:
An example that will give back
[1, 2, 3] is shown below:
Now the following results can occur:
If you want an iterator that would do the following:
You can either copy
Array.prototype's iterator or build something similar. We
will see how to do both:
Array.prototype iterator does is checks the length and yields each and
every index until the length is reached.
Let's try that by ourselves.
This defines a generator function that will keep track of the index that it was on and increment that every time. The index's value will then be yielded.