Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create template.asyncExpression #405

Merged
merged 1 commit into from
Jun 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/__tests__/template-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ while (i < 10) {
)
.toEqual(expected);
});

it('correctly parses expressions without any interpolation', () => {
const expected = 'function() {}';

Expand All @@ -121,6 +120,15 @@ while (i < 10) {
.toEqual(expected);
});

for (const parser of ['babel', 'babylon', 'flow', 'ts', 'tsx']) {
it(`asyncExpression correctly parses expressions with await -- ${parser}`, () => {
const expected = '{\n bar: await baz\n}'
const j = jscodeshift.withParser(parser)

expect(j(j.template.asyncExpression`{\n bar: await baz\n}`).toSource()).toEqual(expected)
})
}

describe('explode arrays', () => {

it('explodes arrays in function definitions', () => {
Expand Down
22 changes: 21 additions & 1 deletion src/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,5 +149,25 @@ module.exports = function withParser(parser) {
return expression;
}

return {statements, statement, expression};
function asyncExpression(template/*, ...nodes*/) {
template = Array.from(template);
if (template.length > 0) {
template[0] = 'async () => (' + template[0];
template[template.length - 1] += ')';
}

const expression = statement.apply(
null,
[template].concat(Array.from(arguments).slice(1))
).expression.body;

// Remove added parens
if (expression.extra) {
expression.extra.parenthesized = false;
}

return expression;
}

return {statements, statement, expression, asyncExpression};
}