Skip to content

Commit

Permalink
Safe spread optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
wcjohnson committed Oct 11, 2017
1 parent 233f224 commit 2bbf09e
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 3 deletions.
18 changes: 18 additions & 0 deletions src/transforms/safe.lsc
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,24 @@ export transformExistentialExpression(path) ->
)

export transformSafeSpreadElement(path) ->
{ node: { argument } } = path
// Optimization: if the thing being spread is already an array, elide
if argument~isa("ArrayExpression"):
path.node._safe = true
return

// Optimization: if spreading an `IfExpr` without an alternate, just add
// `[]` as an alternate if consequent is an array
if (
argument~isa("IfExpression") and
argument.consequent~isa("ArrayExpression") and
(not argument.alternate)
):
argument.alternate = t.arrayExpression()
path.get("argument").replaceWith(argument)
path.node._safe = true
return

{ ref, assign, isComplex } = hoistRef(path, path.node.argument, "ref")

cond = t.conditionalExpression(
Expand Down
4 changes: 1 addition & 3 deletions test/fixtures/comprehensions/multi/expected.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
(() => {
var _ref;

const _arr = [1, 2];

for (let _arr2 = ["buckle", "my", "shoe"], _i = 0, _len = _arr2.length; _i < _len; _i++) {
const e = _arr2[_i];_arr.push(e);
}_arr.push(...(_ref = true ? [3] : void 0, _ref === void 0 ? [] : _ref), 4);
}_arr.push(...(true ? [3] : []), 4);
for (let _arr3 = ["shut", "the", "door"], _i2 = 0, _len2 = _arr3.length; _i2 < _len2; _i2++) {
const e = _arr3[_i2];_arr.push(e);
}_arr.push(5, 6, "pickup sticks");
Expand Down
11 changes: 11 additions & 0 deletions test/fixtures/safe-spread/kitchen-sink/actual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[...expr]

[...[arrayExpr]]

[...if test: someFunction()]

[...if test: [explicitValue]]

[...if test: consequent else: alternate]

[...if test: [consequent] else: [alternate]]
13 changes: 13 additions & 0 deletions test/fixtures/safe-spread/kitchen-sink/expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var _ref, _ref2, _ref3;

[...(expr === void 0 ? [] : expr)];

[...[arrayExpr]];

[...(_ref = test ? someFunction() : void 0, _ref === void 0 ? [] : _ref)];

[...(test ? [explicitValue] : [])];

[...(_ref2 = test ? consequent : alternate, _ref2 === void 0 ? [] : _ref2)];

[...(_ref3 = test ? [consequent] : [alternate], _ref3 === void 0 ? [] : _ref3)];

0 comments on commit 2bbf09e

Please sign in to comment.