Skip to content

Commit

Permalink
feat: support delete operation
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 15, 2023
1 parent c58699b commit ad40a7b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
23 changes: 21 additions & 2 deletions src/proxy/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@ export function proxifyArrayElements<T extends object>(
if (typeof key === "symbol") {
return;
}
const prop = getItem(+key);
const index = +key;
if (Number.isNaN(index)) {
return;
}
const prop = getItem(index);
if (prop) {
return proxify(prop);
}
Expand All @@ -51,7 +55,22 @@ export function proxifyArrayElements<T extends object>(
if (typeof key === "symbol") {
return false;
}
replaceItem(+key, literalToAst(value));
const index = +key;
if (Number.isNaN(index)) {
return false;
}
replaceItem(index, literalToAst(value));
return true;
},
deleteProperty(_, key) {
if (typeof key === "symbol") {
return false;
}
const index = +key;
if (Number.isNaN(index)) {
return false;
}
elements[index] = literalToAst(undefined);
return true;
},
ownKeys() {
Expand Down
12 changes: 12 additions & 0 deletions src/proxy/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ export function proxifyObject<T>(node: ESNode): Proxified<T> {
replaceOrAddProp(key, literalToAst(value));
return true;
},
deleteProperty(_, key) {
if (typeof key !== "string") {
key = String(key);
}
const index = node.properties.findIndex(
(prop) => "key" in prop && "name" in prop.key && prop.key.name === key
);
if (index !== -1) {
node.properties.splice(index, 1);
}
return true;
},
ownKeys() {
return node.properties
.map((prop) => {
Expand Down
24 changes: 23 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe("magicast", () => {
);
});

it("parse, update, generate", () => {
it("function wrapper", () => {
const mod = parseCode(`
export const a: any = { foo: 1}
export default defineConfig({
Expand Down Expand Up @@ -145,4 +145,26 @@ describe("magicast", () => {
});"
`);
});

it("delete property", () => {
const mod = parseCode(`export default { a: 1, b: [1, { foo: 'bar' }] }`);

delete mod.exports.default.b[1].foo;

expect(generate(mod)).toMatchInlineSnapshot(
'"export default { a: 1, b: [1, {}] };"'
);

delete mod.exports.default.b[0];
expect(generate(mod)).toMatchInlineSnapshot(
'"export default { a: 1, b: [undefined, {}] };"'
);

delete mod.exports.default.a;
expect(generate(mod)).toMatchInlineSnapshot(`
"export default {
b: [undefined, {}],
};"
`);
});
});

0 comments on commit ad40a7b

Please sign in to comment.