From 622c25986ea1f5f8c669c3329e16584ffdc10f3e Mon Sep 17 00:00:00 2001 From: so1ve Date: Tue, 5 Sep 2023 09:28:58 -0400 Subject: [PATCH] fix: correctly handle blockstatement (#86) --- src/preprocess.test.ts | 3 +++ src/printNodeWithBrackets.ts | 15 +++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/preprocess.test.ts b/src/preprocess.test.ts index 4105314e..66dfb6ea 100644 --- a/src/preprocess.test.ts +++ b/src/preprocess.test.ts @@ -16,6 +16,9 @@ describe("preprocess", () => { [`for (const a of b) { c; }`, `for (const a of b) { c; }`], [`if (a) b;`, `if (a) { b; }`], [`if (a) { b; }`, `if (a) { b; }`], + [`if (a) b; else c;`, `if (a) { b; } else { c; }`], + [`if (a) b; else { c; }`, `if (a) { b; } else { c; }`], + [`if (a) b; else if (b) c;`, `if (a) { b; } else if (b) { c; }`], ["let a; let a;", "let a; let a;"], ["foo; import a from 'bar'", "foo; import a from 'bar'"], ["return;", "return;"], diff --git a/src/printNodeWithBrackets.ts b/src/printNodeWithBrackets.ts index 0e383212..a9773146 100644 --- a/src/printNodeWithBrackets.ts +++ b/src/printNodeWithBrackets.ts @@ -53,9 +53,20 @@ export function printNodeWithBrackets(code: string, node: CollectibleNode) { return [ code.slice(node.start!, node.test.end!), ") { ", - code.slice(node.consequent.start!, node.end!), + code.slice(node.consequent.start!, node.consequent.end!), " }", - ].join(""); + node.alternate && [ + " else ", + node.alternate.type !== "IfStatement" && [ + node.alternate.type !== "BlockStatement" && "{ ", + code.slice(node.alternate.start!, node.alternate.end!), + node.alternate.type !== "BlockStatement" && " }", + ], + ], + ] + .flat(Infinity) + .filter(Boolean) + .join(""); case "WhileStatement": return [