fix: early return when instance is not iterable#10396
fix: early return when instance is not iterable#10396nicolo-ribaudo merged 3 commits intobabel:masterfrom
Conversation
| // _i = _iterator | ||
| // _s = _step | ||
|
|
||
| if (!Symbol.iterator in Object(arr)) return; |
There was a problem hiding this comment.
The iterableToArray has guarded this check with an arguments check
export default function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === "[object Arguments]"
) return Array.from(iter);
}But
(function () { return Symbol.iterator in Object(arguments) })()returns true in Chrome 76. I am not sure if this behavior is inconsistent across different browsers.
There was a problem hiding this comment.
Oh, there is a browser support matrix on arguments[@@iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator
|
Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/11483/ |
|
Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/11471/ |
Actually yes, we need to check for arguments. This is because arguments can't be polyfilled (becaue it is re-created every time), so Symbol.iterator in Object(arguments) will always be false in old browsers, even with a polyfill.
Babel output changed. See babel/babel#10396
The
slicedToArrayis supposed to thrownonIterableResterror when applied to an non-iterable instance. However, theiterableToArrayLimitwill always throw error inarr[Symbol.iterator]whenarris not iterable.Here we early return in
iterableToArrayLimitso that we can offer better error message in runtime. Note that by doing so we also aligniterableToArrayLimitwithiterableToArray.