Correctly transform spreads of arrays with holes (#13439)

* Correctly transform spreads of arrays with holes

* Use `arrayWithoutHoles` helper

* Add exec test

* Update for Babel 8

Co-authored-by: phapp88 <phapp1988@gmail.com>
This commit is contained in:
Nicolò Ribaudo 2021-06-10 12:34:42 +02:00 committed by GitHub
parent 366e6d9251
commit e914d1219f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 38 additions and 3 deletions

View File

@ -20,6 +20,10 @@ export default declare((api, options) => {
}
}
function hasHole(spread) {
return spread.elements.some(el => el === null);
}
function hasSpread(nodes) {
for (let i = 0; i < nodes.length; i++) {
if (t.isSpreadElement(nodes[i])) {
@ -35,14 +39,27 @@ export default declare((api, options) => {
return [];
}
function build(props: Array, scope) {
function build(props: Array, scope, file) {
const nodes = [];
let _props = [];
for (const prop of props) {
if (t.isSpreadElement(prop)) {
_props = push(_props, nodes);
nodes.push(getSpreadLiteral(prop, scope));
let spreadLiteral = getSpreadLiteral(prop, scope);
if (t.isArrayExpression(spreadLiteral) && hasHole(spreadLiteral)) {
spreadLiteral = t.callExpression(
file.addHelper(
process.env.BABEL_8_BREAKING
? "arrayLikeToArray"
: "arrayWithoutHoles",
),
[spreadLiteral],
);
}
nodes.push(spreadLiteral);
} else {
_props.push(prop);
}
@ -62,7 +79,7 @@ export default declare((api, options) => {
const elements = node.elements;
if (!hasSpread(elements)) return;
const nodes = build(elements, scope);
const nodes = build(elements, scope, this);
let first = nodes[0];
// If there is only one element in the ArrayExpression and

View File

@ -0,0 +1,2 @@
let arr = ['a', ...['b',,'c']];
expect(2 in arr).toBe(true);

View File

@ -0,0 +1,2 @@
var a = [...['a',, 'b']];
var b = ['a', ...['b',, 'c']];

View File

@ -0,0 +1,3 @@
{
"BABEL_8_BREAKING": false
}

View File

@ -0,0 +1,2 @@
var a = babelHelpers.arrayWithoutHoles(['a',, 'b']);
var b = ['a'].concat(babelHelpers.arrayWithoutHoles(['b',, 'c']));

View File

@ -0,0 +1,2 @@
let arr = ['a', ...['b',,'c']];
expect(2 in arr).toBe(true);

View File

@ -0,0 +1,2 @@
var a = [...['a',, 'b']];
var b = ['a', ...['b',, 'c']];

View File

@ -0,0 +1,3 @@
{
"BABEL_8_BREAKING": true
}

View File

@ -0,0 +1,2 @@
var a = babelHelpers.arrayLikeToArray(['a',, 'b']);
var b = ['a'].concat(babelHelpers.arrayLikeToArray(['b',, 'c']));