Skip to content

Commit

Permalink
Correctly transform spreads of arrays with holes
Browse files Browse the repository at this point in the history
  • Loading branch information
phapp88 authored and nicolo-ribaudo committed Jun 9, 2021
1 parent d3f4c22 commit 87c5f03
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/babel-plugin-transform-spread/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ export default declare((api, options) => {
}
}

function hasHole(spread) {
const elements = spread.elements;
for (let i = 0; i < elements.length; i++) {
if (elements[i] === null) {
return true;
}
}
return false;
}

function hasSpread(nodes) {
for (let i = 0; i < nodes.length; i++) {
if (t.isSpreadElement(nodes[i])) {
Expand All @@ -35,14 +45,21 @@ 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("toConsumableArray"),
[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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
var a = [...['a',, 'b']];
var b = ['a', ...['b',, 'c']];
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
var a = babelHelpers.toConsumableArray(['a',, 'b']);
var b = ['a'].concat(babelHelpers.toConsumableArray(['b',, 'c']));

0 comments on commit 87c5f03

Please sign in to comment.