Skip to content

Commit 90040ee

Browse files
committed
feat: support more array operation
1 parent ad40a7b commit 90040ee

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/proxy/array.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,25 @@ export function proxifyArrayElements<T extends object>(
3030
shift() {
3131
return proxify(elements.shift() as any);
3232
},
33+
splice(start: number, deleteCount: number, ...items: any[]) {
34+
const deleted = elements.splice(
35+
start,
36+
deleteCount,
37+
...items.map(n => literalToAst(n))
38+
);
39+
return deleted.map(n => proxify(n as any));
40+
},
41+
find(predicate: (value: any, index: number, arr: any[]) => boolean) {
42+
// eslint-disable-next-line unicorn/no-array-callback-reference
43+
return elements.map((n) => proxify(n as any)).find(predicate);
44+
},
45+
findIndex(predicate: (value: any, index: number, arr: any[]) => boolean) {
46+
// eslint-disable-next-line unicorn/no-array-callback-reference
47+
return elements.map((n) => proxify(n as any)).findIndex(predicate);
48+
},
49+
includes (value: any) {
50+
return elements.map((n) => proxify(n as any)).includes(value);
51+
},
3352
toJSON() {
3453
return elements.map((n) => proxify(n as any));
3554
},

test/index.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,4 +167,39 @@ describe("magicast", () => {
167167
};"
168168
`);
169169
});
170+
171+
it("array operations", () => {
172+
const mod = parseCode(`export default [1, 2, 3, 4, 5]`);
173+
174+
expect(mod.exports.default.length).toBe(5);
175+
expect(mod.exports.default.includes(5)).toBe(true);
176+
expect(mod.exports.default.includes(6)).toBe(false);
177+
178+
const deleted = mod.exports.default.splice(1, 3, { foo: 'bar' }, 'bar')
179+
180+
expect(deleted).toEqual([2, 3, 4])
181+
182+
expect(generate(mod)).toMatchInlineSnapshot(
183+
`
184+
"export default [
185+
1,
186+
{
187+
foo: \\"bar\\",
188+
},
189+
\\"bar\\",
190+
5,
191+
];"
192+
`
193+
);
194+
195+
const foundIndex = mod.exports.default.findIndex((item) => item.foo === 'bar')
196+
const found = mod.exports.default.find((item) => item.foo === 'bar')
197+
198+
expect(foundIndex).toBe(1)
199+
expect(found).toMatchInlineSnapshot(`
200+
{
201+
"foo": "bar",
202+
}
203+
`)
204+
})
170205
});

0 commit comments

Comments
 (0)