From 4fb7a82d90622546f5b3e094564e6392432a30d5 Mon Sep 17 00:00:00 2001 From: ticklepoke Date: Tue, 6 Jul 2021 20:24:38 +0800 Subject: [PATCH] feat(let-const): Support for array patterns --- .../convert-let-const.input.js | 2 ++ .../convert-let-const.output.js | 2 ++ src/convert-let-const.ts | 23 ++++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/__testfixtures__/convert-let-const.input.js b/src/__testfixtures__/convert-let-const.input.js index f1af2fb..36107e4 100644 --- a/src/__testfixtures__/convert-let-const.input.js +++ b/src/__testfixtures__/convert-let-const.input.js @@ -36,3 +36,5 @@ try { let a = 1; a++; } catch (err) {} +let [d] = foo(); +let [e, f] = bar(); diff --git a/src/__testfixtures__/convert-let-const.output.js b/src/__testfixtures__/convert-let-const.output.js index 97693a5..255c6f9 100644 --- a/src/__testfixtures__/convert-let-const.output.js +++ b/src/__testfixtures__/convert-let-const.output.js @@ -36,3 +36,5 @@ try { let a = 1; a++; } catch (err) {} +const [d] = foo(); +const [e, f] = bar(); \ No newline at end of file diff --git a/src/convert-let-const.ts b/src/convert-let-const.ts index b6a443c..99543ae 100644 --- a/src/convert-let-const.ts +++ b/src/convert-let-const.ts @@ -5,7 +5,6 @@ import { ExpressionStatement, FileInfo, FunctionDeclaration, - Property, TryStatement, VariableDeclaration, } from 'jscodeshift'; @@ -72,6 +71,16 @@ function handleVariableDeclaration(node: VariableDeclaration, depth: number, sto } } }); + } else if (decl.id.type === 'ArrayPattern') { + decl.id.elements.forEach((el) => { + if (el?.type === 'Identifier') { + if (store.has(el.name)) { + store.get(el.name)?.push(depth); + } else { + store.set(el.name, [depth]); + } + } + }); } if (decl.init?.type === 'FunctionExpression') { decl.init.body = handleBlock(decl.init.body, depth + 1, store); @@ -137,6 +146,18 @@ function convertLetConst(body: StatementKind[], depth: number, store: Store): St if (inStore) { stmt.kind = 'const'; } + } else if (decl.id.type === 'ArrayPattern') { + const inStore = decl.id.elements.every((el) => { + if (el?.type === 'Identifier') { + if (store.get(el.name)?.includes(depth)) { + return true; + } + return false; + } + }); + if (inStore) { + stmt.kind = 'const'; + } } } });