Skip to content

Commit

Permalink
feat: convert object/array destructuring default parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Mar 22, 2024
1 parent 98ca4a9 commit 5ff3044
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
16 changes: 16 additions & 0 deletions packages/webcrack/src/transpile/test/default-parameters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ describe('Babel', () => {
function f(e, x = {}, _param, _param2, _param3, y) {}
`));

test('default destructuring parameter', () =>
expectJS(`
function f() {
let {
x,
y
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let [z] = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
}
`).toMatchInlineSnapshot(`
function f({
x,
y
} = {}, [z] = []) {}
`));

test('default parameter (loose)', () =>
expectJS(`
function f(x, y) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ export default {
const defaultExpression = m.capture(m.anyExpression());
const index = m.capture(m.numericLiteral());
const varName = m.capture(m.identifier());
const varId = m.capture(m.or(m.identifier(), m.arrayPattern(), m.objectPattern()));

// Example: arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
const defaultParam = m.variableDeclaration(undefined, [
m.variableDeclarator(
varName,
varId,
m.conditionalExpression(
m.logicalExpression(
'&&',
Expand Down Expand Up @@ -58,7 +59,7 @@ export default {
// Example: var y = arguments.length > 1 ? arguments[1] : undefined;
const normalParam = m.variableDeclaration(undefined, [
m.variableDeclarator(
varName,
varId,
m.conditionalExpression(
m.binaryExpression(
'>',
Expand Down Expand Up @@ -86,7 +87,7 @@ export default {
fn.params[i] = t.identifier(path.scope.generateUid('param'));
}
fn.params[index.current!.value] = t.assignmentPattern(
varName.current!,
varId.current!,
defaultExpression.current!,
);
path.remove();
Expand All @@ -95,7 +96,7 @@ export default {
for (let i = fn.params.length; i < index.current!.value; i++) {
fn.params[i] = t.identifier(path.scope.generateUid('param'));
}
fn.params[index.current!.value] = varName.current!;
fn.params[index.current!.value] = varId.current!;
path.remove();
this.changes++;
}
Expand Down

0 comments on commit 5ff3044

Please sign in to comment.