Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 / Babel spread error with Set

I have the following code, simplified from a real-world example.

let arr = [0,1,2],
    s = new Set(arr);

let arr2 = [...s];
alert('3 == ' + arr2.length);

The problem is that this fails, and produces an empty arr2 on Google Chrome which has a native Set implementation, but a polyfilled Array.from. Amusingly, it works properly on IE11, which has a polyfilled Array.from AND Set.

Babel converts the spread Set to this

var arr2 = [].concat(_toConsumableArray(s));

and _toConsumableArray returns Array.from. I've set a breakpoint inside of _toConsumableArray and I can see it producing an empty Array through the call to Array.from.

My question is, is this a bug in the Array.from polyfill, in that it doesn't properly process a native (not polyfilled) Set, or is the problem with the Babel code, in that Array.from(x) is not a perfect equivalent for ...x (when x is not an array).

like image 346
Adam Rackis Avatar asked Aug 14 '15 00:08

Adam Rackis


1 Answers

I can see it producing an empty Array through the call to Array.from. Is this a bug in MDN's Array.from polyfill?

Not really a bug, but actually properly documented:

In addition, since true iterables can not be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ECMA-262.

I assume that refers to the lack of Symbol.iterator in ES5.

like image 153
Bergi Avatar answered Nov 13 '22 04:11

Bergi