Skip to content
This repository has been archived by the owner on Sep 25, 2019. It is now read-only.

Commit

Permalink
Merge pull request #161 from Rich-Harris/gh-159
Browse files Browse the repository at this point in the history
preserve parens around x in y in for loop head
  • Loading branch information
Rich-Harris committed May 19, 2017
2 parents 85d7a17 + a25c653 commit f3e7627
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/program/types/ParenthesizedExpression.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ function shouldRemoveParens ( expression, parent ) {
if ( parent.left.contains( expression ) ) return false;
}

// special case — `for (x=(y in z);...)`. This is a bit ugly
if ( expression.type === 'BinaryExpression' && expression.operator === 'in' ) {
let maybeForStatement = parent;
while ( maybeForStatement && maybeForStatement.type !== 'ForStatement' ) {
maybeForStatement = maybeForStatement.parent;
}

if ( maybeForStatement && maybeForStatement.init && maybeForStatement.init.contains( parent ) ) return false;
}

const expressionPrecedence = expression.getPrecedence();
const parentPrecedence = parent.getPrecedence();

Expand Down
18 changes: 18 additions & 0 deletions test/samples/loops.js
Original file line number Diff line number Diff line change
Expand Up @@ -245,5 +245,23 @@ module.exports = [
do_anything()
}`,
output: `for(let f=1;condition;f++)do_anything()`
},

{
description: 'preserves parens around `x in y` expression',
input: `
for (any_value = ("key" in any_object); any_condition;) {
any_fn()
}`,
output: `for(any_value=("key" in any_object);any_condition;)any_fn()`
},

{
description: 'preserves parens around `x in y` expression in var declaration',
input: `
for (var any_value = ("key" in any_object); any_condition;) {
any_fn()
}`,
output: `for(var any_value=("key" in any_object);any_condition;)any_fn()`
}
];

0 comments on commit f3e7627

Please sign in to comment.