Skip to content

Commit

Permalink
Correctly transform spreads of arrays with holes (#13439)
Browse files Browse the repository at this point in the history
* Correctly transform spreads of arrays with holes

* Use `arrayWithoutHoles` helper

* Add exec test

* Update for Babel 8

Co-authored-by: phapp88 <phapp1988@gmail.com>
  • Loading branch information
nicolo-ribaudo and phapp88 committed Jun 10, 2021
1 parent 366e6d9 commit e914d12
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/babel-plugin-transform-spread/src/index.js
Expand Up @@ -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])) {
Expand All @@ -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);
}
Expand All @@ -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
Expand Down
@@ -0,0 +1,2 @@
let arr = ['a', ...['b',,'c']];
expect(2 in arr).toBe(true);
@@ -0,0 +1,2 @@
var a = [...['a',, 'b']];
var b = ['a', ...['b',, 'c']];
@@ -0,0 +1,3 @@
{
"BABEL_8_BREAKING": false
}
@@ -0,0 +1,2 @@
var a = babelHelpers.arrayWithoutHoles(['a',, 'b']);
var b = ['a'].concat(babelHelpers.arrayWithoutHoles(['b',, 'c']));
@@ -0,0 +1,2 @@
let arr = ['a', ...['b',,'c']];
expect(2 in arr).toBe(true);
@@ -0,0 +1,2 @@
var a = [...['a',, 'b']];
var b = ['a', ...['b',, 'c']];
@@ -0,0 +1,3 @@
{
"BABEL_8_BREAKING": true
}
@@ -0,0 +1,2 @@
var a = babelHelpers.arrayLikeToArray(['a',, 'b']);
var b = ['a'].concat(babelHelpers.arrayLikeToArray(['b',, 'c']));

0 comments on commit e914d12

Please sign in to comment.