Single argument arrow functions (#1186)

swc_ecma_codegen:
 - Remove parens from arrow functions when possible.
 - Remove space after prop keys when minifying.
 - Remove line break after expressions when minifying.
 - Remove space after generator `*` when minifying.
This commit is contained in:
Brad Dunbar 2020-10-27 02:08:05 -04:00 committed by GitHub
parent 6e9d06e95a
commit 667a8c72c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 48 additions and 17 deletions

View File

@ -59,9 +59,11 @@ impl<'a> Emitter<'a> {
keyword!("function");
if node.function.is_generator {
punct!("*");
formatting_space!();
} else {
space!();
}
space!();
emit!(node.ident);
self.emit_fn_trailing(&node.function)?;
@ -100,3 +102,27 @@ impl<'a> Emitter<'a> {
}
}
}
#[cfg(test)]
mod tests {
use crate::tests::assert_min;
#[test]
fn issue_275() {
assert_min(
"function* foo(){
yield getServiceHosts()
}",
"function*foo(){yield getServiceHosts();}",
);
}
#[test]
fn single_argument_arrow_expression() {
assert_min("function* f(){ yield x => x}", "function*f(){yield x=>x;}");
assert_min(
"function* f(){ yield ({x}) => x}",
"function*f(){yield({x})=>x;}",
);
}
}

View File

@ -188,14 +188,4 @@ mod tests {
fn regression_increments() {
assert_min("x++ + ++y", "x++ + ++y;");
}
#[test]
fn issue_275() {
assert_min(
"function* foo(){
yield getServiceHosts()
}",
"function* foo(){yield getServiceHosts();}",
);
}
}

View File

@ -644,9 +644,20 @@ impl<'a> Emitter<'a> {
if node.is_generator {
punct!("*")
}
punct!("(");
let parens = !self.cfg.minify
|| match node.params.as_slice() {
[Pat::Ident(_)] => false,
_ => true,
};
if parens {
punct!("(");
}
self.emit_list(node.span, Some(&node.params), ListFormat::CommaListElements)?;
punct!(")");
if parens {
punct!(")");
}
punct!("=>");
emit!(node.body);
@ -1114,7 +1125,9 @@ impl<'a> Emitter<'a> {
self.wr.increase_indent()?;
emit!(expr);
self.wr.decrease_indent()?;
self.wr.write_line()?;
if !self.cfg.minify {
self.wr.write_line()?;
}
}
}
}
@ -1808,7 +1821,7 @@ impl<'a> Emitter<'a> {
self.emit_leading_comments_of_pos(node.span().lo())?;
emit!(node.key);
space!();
formatting_space!();
if let Some(ref value) = node.value {
punct!("=");
emit!(node.value);

View File

@ -197,8 +197,10 @@ impl StartsWithAlphaNum for Expr {
_ => false,
},
// TODO(kdy1): Support `v => {}`
Expr::Arrow(ArrowExpr { .. }) => false,
Expr::Arrow(ref expr) => match expr.params.as_slice() {
[p] => p.starts_with_alpha_num(),
_ => false,
},
Expr::Update(ref expr) => {
if expr.prefix {