From 955a2c1472e7748c598e3ea08cad4f2d8a81d2a0 Mon Sep 17 00:00:00 2001 From: Lucas Duailibe Date: Sun, 10 Sep 2017 12:34:55 -0300 Subject: [PATCH] Keep conditional expressions in one line on method chains (#2784) Fixes #2775. This commit will make conditional expressions to match the behavior of logical expression in method chains: ```js (a ? b : c).map() // if the conditional fits in oneline (a ? b : c) .map() // if the conditional doesn't fit (a ? b : c) .map() ``` --- src/printer.js | 4 +++- .../__snapshots__/jsfmt.spec.js.snap | 21 +++++++++++++++++++ tests/method-chain/conditional.js | 9 ++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/method-chain/conditional.js diff --git a/src/printer.js b/src/printer.js index 6b333463..0d16304b 100644 --- a/src/printer.js +++ b/src/printer.js @@ -3705,7 +3705,9 @@ function printMemberChain(path, options, print) { groups.length <= cutoff && !hasComment && // (a || b).map() should be break before .map() instead of || - groups[0][0].node.type !== "LogicalExpression" + groups[0][0].node.type !== "LogicalExpression" && + // (a ? b : c).map() should be break before .map() instead of ? + groups[0][0].node.type !== "ConditionalExpression" ) { return group(oneLine); } diff --git a/tests/method-chain/__snapshots__/jsfmt.spec.js.snap b/tests/method-chain/__snapshots__/jsfmt.spec.js.snap index da56e5a0..a60288c2 100644 --- a/tests/method-chain/__snapshots__/jsfmt.spec.js.snap +++ b/tests/method-chain/__snapshots__/jsfmt.spec.js.snap @@ -416,6 +416,27 @@ exports[`computed-merge.js 1`] = ` `; +exports[`conditional.js 1`] = ` +(valid + ? helper.responseBody(this.currentUser) + : helper.response(401)) +.map(res => res.json()); + +(valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(defaultUser)) +.map(res => res.json()); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +(valid ? helper.responseBody(this.currentUser) : helper.response(401)) + .map(res => res.json()); + +(valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(defaultUser)) + .map(res => res.json()); + +`; + exports[`first_long.js 1`] = ` export default function theFunction(action$, store) { return action$.ofType(THE_ACTION).switchMap(action => Observable diff --git a/tests/method-chain/conditional.js b/tests/method-chain/conditional.js new file mode 100644 index 00000000..5d3299d8 --- /dev/null +++ b/tests/method-chain/conditional.js @@ -0,0 +1,9 @@ +(valid + ? helper.responseBody(this.currentUser) + : helper.response(401)) +.map(res => res.json()); + +(valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(defaultUser)) +.map(res => res.json());