What Is The Technical Definition Of A Javascript Iterable And How Do You Test For It?
Solution 1:
What is the real definition of a Javascript iterable using the term as the ES6 specification does?
§25.1.1.1 defines "The Iterable Interface".
They're objects with a Symbol.iterator
-keyed method that returns a valid Iterator (which in turn is an object expected to behave as it should according to §25.1.1.2).
How do you test for it in ES6 Javascript?
We cannot test what the @@iterator
method returns without calling it, and we cannot test whether the result conforms to the Iterator
interface without trying to run it. The best bet would be to do
functionlooksIterable(o) {
returntypeof o[Symbol.iterator] == "function";
}
however I wouldn't usually test for this but simply let it fail with an exception when it's not iterable.
How should you iterate a generic iterable?
Don't use forEach
. (In fact, never use forEach
anywhere in ES6).
The proper way to iterate is a for (… of …)
loop. It does all the checking for iterability (using the abstract GetIterator
operation and running (and even closing) the iterator, and throws appropriate TypeError
s when used on non-iterable values.
Solution 2:
There's a special property on the Symbol constructor, Symbol.iterator
, whose value is that, uhh, I guess you'd say "conceptual" property name "@@iterator". So you can create an iterator method for an object like this:
object[Symbol.iterator] = function* () {
// do something that makes sense
};
You can also test to see if some object is an iterator by doing
if (Symbol.iterator in object)
(and maybe also checking to see if it's a function). Now those iterator functions (the value of the Symbol.iterator
property) are generator functions (not the *
that I edited into the example). Thus you start them and get values by first calling the function and saving the returned object, and then calling .next()
. That'll get you an object with value
and done
properties.
You can alternatively let for ... of
or the "spread" ...
operator worry about the iterator function.
Post a Comment for "What Is The Technical Definition Of A Javascript Iterable And How Do You Test For It?"