From 005959df3923395774efd14582e17e60abc67d64 Mon Sep 17 00:00:00 2001 From: coderaiser Date: Thu, 19 Oct 2023 23:06:59 +0300 Subject: [PATCH] feature: goldstein: convert: if let --- packages/convert/apply-if-let/index.js | 18 ++++++++++++++++++ packages/convert/index.js | 2 ++ packages/convert/index.spec.js | 23 +++++++++++++++++++++++ packages/printer/visitors/if-statement.js | 3 ++- 4 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 packages/convert/apply-if-let/index.js diff --git a/packages/convert/apply-if-let/index.js b/packages/convert/apply-if-let/index.js new file mode 100644 index 0000000..5aeadea --- /dev/null +++ b/packages/convert/apply-if-let/index.js @@ -0,0 +1,18 @@ +import {types} from 'putout'; +const { + VariableDeclaration, + VariableDeclarator, +} = types; + +export const report = () => `Use 'add-array'`; +export const replace = () => ({ + '{let __a = __b; if (__c) __d}': ({__a, __b}, path) => { + const ifPath = path.get('body.1'); + ifPath.node.test = VariableDeclaration('let', [ + VariableDeclarator(__a, __b), + ]); + + return ifPath; + }, +}); + diff --git a/packages/convert/index.js b/packages/convert/index.js index 66f7ccc..4bab979 100644 --- a/packages/convert/index.js +++ b/packages/convert/index.js @@ -4,6 +4,7 @@ import {print} from '../printer/index.js'; import * as removeImportTry from './remove-import-try/index.js'; import * as applyTry from './apply-try/index.js'; import * as addArray from './add-array/index.js'; +import * as applyIfLet from './apply-if-let/index.js'; import { fixEmpty, parse, @@ -15,6 +16,7 @@ export const convert = (source) => { transform(ast, source, { plugins: [ ['add-array', addArray], + ['apply-if-let', applyIfLet], ['apply-try', applyTry], ['remove-import-try', removeImportTry], ], diff --git a/packages/convert/index.spec.js b/packages/convert/index.spec.js index be8dddb..9cfae0e 100644 --- a/packages/convert/index.spec.js +++ b/packages/convert/index.spec.js @@ -44,3 +44,26 @@ test('goldstein: convert: add-array', (t) => { t.equal(result, expected); t.end(); }); + +test('goldstein: convert: convert-if-let', (t) => { + const source = montag` + { + let a = b?.c; + + if (a) { + log(a); + } + } + `; + + const result = convert(source); + + const expected = montag` + if let a = b?.c { + log(a); + }\n + `; + + t.equal(result, expected); + t.end(); +}); diff --git a/packages/printer/visitors/if-statement.js b/packages/printer/visitors/if-statement.js index 8f273e8..5da34a1 100644 --- a/packages/printer/visitors/if-statement.js +++ b/packages/printer/visitors/if-statement.js @@ -1,12 +1,13 @@ import {visitors as v} from '@putout/printer'; export const IfStatement = (path, printer, semantics) => { - const {print} = printer; + const {print, indent} = printer; const {node} = path; if (!node.goldsteinIf) return v.IfStatement(path, printer, semantics); + indent(); print('if '); print('__test'); print(' ');