Skip to content

Commit

Permalink
object spread: also drop non-nullish constants (e.g. { ...true }) (#…
Browse files Browse the repository at this point in the history
…1141)

This is a follow-up to 6f04338 (#1004)
  • Loading branch information
WofWca committed Apr 23, 2024
1 parent 096cac0 commit db932f0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
17 changes: 8 additions & 9 deletions lib/compress/index.js
Expand Up @@ -3758,7 +3758,7 @@ def_optimize(AST_Array, function(self, compressor) {
return self;
});

function inline_object_prop_spread(props, compressor) {
function inline_object_prop_spread(props) {
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (prop instanceof AST_Expansion) {
Expand All @@ -3770,15 +3770,14 @@ function inline_object_prop_spread(props, compressor) {
props.splice(i, 1, ...expr.properties);
// Step back one, as the property at i is now new.
i--;
} else if (expr instanceof AST_Constant
&& !(expr instanceof AST_String)) {
} else if ((
// `expr.is_constant()` returns `false` for `AST_RegExp`, so need both.
expr instanceof AST_Constant
|| expr.is_constant()
) && !(expr instanceof AST_String)) {
// Unlike array-like spread, in object spread, spreading a
// non-iterable value silently does nothing; it is thus safe
// to remove. AST_String is the only iterable AST_Constant.
props.splice(i, 1);
i--;
} else if (is_nullish(expr, compressor)) {
// Likewise, null and undefined can be silently removed.
// to remove. AST_String is the only iterable constant.
props.splice(i, 1);
i--;
}
Expand All @@ -3791,7 +3790,7 @@ def_optimize(AST_Object, function(self, compressor) {
if (optimized !== self) {
return optimized;
}
inline_object_prop_spread(self.properties, compressor);
inline_object_prop_spread(self.properties);
return self;
});

Expand Down
29 changes: 26 additions & 3 deletions test/compress/expansions.js
Expand Up @@ -103,7 +103,31 @@ object_spread: {
]
}

object_spread_nullish_undefined: {
object_spread_constant: {
input: {
id({
...null,
...undefined,
...true,
...void 0,
...!0,
...~"foo",
.../baz/,
...-/baz2/,

..."bar",
});
}

expect: {
id({
..."bar"
})
}
}

// https://github.com/terser/terser/pull/1071
object_spread_inline_after_dropping_undefined: {
input: {
let o = { ...undefined, ...{a: true} }
id(o);
Expand All @@ -114,8 +138,7 @@ object_spread_nullish_undefined: {
id(o)
}
}

object_spread_nullish_null: {
object_spread_inline_after_dropping_null: {
input: {
let o = { ...null, ...{a: true} }
id(o);
Expand Down

0 comments on commit db932f0

Please sign in to comment.