Skip to content

automatically optimize array-destructuring #3711

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

Closed
wants to merge 2 commits into from
Closed
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
2 changes: 2 additions & 0 deletions resources/build-npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'node:path';
import ts from 'typescript';

import { inlineInvariant } from './inline-invariant.js';
import { transformArrayDestructuring } from './transform-array-destruct.js'
import {
localRepoPath,
readdirRecursive,
Expand Down Expand Up @@ -51,6 +52,7 @@ tsHost.writeFile = writeGeneratedFile;

const tsProgram = ts.createProgram(['src/index.ts'], tsOptions, tsHost);
const tsResult = tsProgram.emit(undefined, undefined, undefined, undefined, {
before: [transformArrayDestructuring()],
after: [inlineInvariant],
});
assert(
Expand Down
37 changes: 37 additions & 0 deletions resources/transform-array-destruct.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import * as ts from 'typescript';

export function transformArrayDestructuring() {
return (context: ts.TransformationContext) => {
const { factory } = context;

return (sourceFile: ts.SourceFile) => {
const visitor = (node: ts.Node): ts.Node => {
if (ts.isArrayBindingPattern(node)) {
const elements = node.elements
.map((el, i) => {
if (!el.getText()) {
return undefined;
}
return { key: String(i), name: el.getText() };
})
.filter(Boolean);

const els = elements
.map((el) => {
if (!el) {
return undefined;
}
const key = factory.createIdentifier(el.key);
const name = factory.createIdentifier(el.name);
return factory.createBindingElement(undefined, key, name);
})
.filter(Boolean) as Array<ts.BindingElement>;
return factory.createObjectBindingPattern(els);
}

return ts.visitEachChild(node, visitor, context);
};
return ts.visitNode(sourceFile, visitor);
};
};
}