Skip to content

Commit

Permalink
feat(typescript): support ObjectPattern (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
tyankatsu0105 committed Sep 13, 2020
1 parent 594bc13 commit 3fdc74e
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 7 deletions.
19 changes: 18 additions & 1 deletion src/shared/helpers/parse/__test__/fixtures/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,21 @@ export const fn2 = (x, y) => x + y, fn3 = () => 1;

export function fn4() { return 1 };

function fn5() { return 1 };
function fn5() { return 1 };

const includeSomeFn = {
fn6() {
return 1
},
fn7() {
return 1
},

prop: {
insideFn(){
return 1
}
}
}

export const { fn6, fn7, prop: { insideFn } } = includeSomeFn
10 changes: 9 additions & 1 deletion src/shared/helpers/parse/__test__/parse-typescript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,15 @@ describe('parse-typescrript', () => {
const { ast } = getAST('function.ts');

const { exportItems } = getExportItems(ast);
expect(exportItems).toEqual(['fn', 'fn2', 'fn3', 'fn4']);
expect(exportItems).toEqual([
'fn',
'fn2',
'fn3',
'fn4',
'fn6',
'fn7',
'insideFn',
]);
});

it('Class', () => {
Expand Down
37 changes: 32 additions & 5 deletions src/shared/helpers/parse/parse-typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,27 @@ import {

import { Generate } from '../../../types';

const traverseObjectPattern = (
properties: (
| TSESTree.PropertyComputedName
| TSESTree.PropertyNonComputedName
| TSESTree.RestElement
)[],
callback: (
property: TSESTree.PropertyComputedName | TSESTree.PropertyNonComputedName
) => void
) => {
for (const property of properties) {
if (property.type === AST_NODE_TYPES['Property']) {
if (property.value.type === AST_NODE_TYPES['Identifier']) {
callback(property);
} else if (property.value.type === AST_NODE_TYPES['ObjectPattern']) {
traverseObjectPattern(property.value.properties, callback);
}
}
}
};

/**
* Get names at "Identifier"
* Only support ES modules
Expand All @@ -31,11 +52,17 @@ export const getExportItems = (ast: TSESTree.Program) => {

simpleTraverse(filterdAst, {
enter(node) {
if (
node.type === AST_NODE_TYPES['VariableDeclarator'] &&
node.id.type === AST_NODE_TYPES['Identifier']
) {
exportItems.push(node.id.name);
if (node.type === AST_NODE_TYPES['VariableDeclarator']) {
if (node.id.type === AST_NODE_TYPES['Identifier']) {
exportItems.push(node.id.name);
}

if (node.id.type === AST_NODE_TYPES['ObjectPattern']) {
traverseObjectPattern(node.id.properties, (property) => {
property.value.type === AST_NODE_TYPES['Identifier'] &&
exportItems.push(property.value.name);
});
}
}

if (node.type === AST_NODE_TYPES['FunctionDeclaration'] && node.id) {
Expand Down

0 comments on commit 3fdc74e

Please sign in to comment.