Skip to content

Commit 54a39c0

Browse files
committed
fix: Select empty arrays when nesting a P.array() and a P.select()
1 parent 3356784 commit 54a39c0

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/patterns.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,13 @@ export function array<
9292

9393
let selections: Record<string, unknown[]> = {};
9494

95+
if (value.length === 0) {
96+
getSelectionKeys(pattern).forEach((key) => {
97+
selections[key] = [];
98+
});
99+
return { matched: true, selections };
100+
}
101+
95102
const selector = (key: string, value: unknown) => {
96103
selections[key] = (selections[key] || []).concat([value]);
97104
};

tests/select.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,4 +434,39 @@ describe('select', () => {
434434
.exhaustive();
435435
});
436436
});
437+
438+
it('Issue #95: P.select() on empty arrays should return an empty array', () => {
439+
const res = match({ a: [], b: ['text'] })
440+
.with(
441+
{ a: P.array(P.select('a')), b: P.array(P.select('b')) },
442+
({ a, b }) => {
443+
type t = Expect<Equal<typeof a, string[]>>;
444+
type t2 = Expect<Equal<typeof b, string[]>>;
445+
return { a, b };
446+
}
447+
)
448+
.otherwise(() => null);
449+
450+
expect(res).toEqual({ a: [], b: ['text'] });
451+
452+
// Should work with deeply nested selections as well
453+
const res2 = match<{ a: { prop: number }[] }>({ a: [] })
454+
.with({ a: P.array({ prop: P.select('a') }) }, ({ a }) => {
455+
type t = Expect<Equal<typeof a, number[]>>;
456+
return { a };
457+
})
458+
.otherwise(() => null);
459+
460+
expect(res2).toEqual({ a: [] });
461+
462+
// P.select of arrays shouldn't be affected
463+
const res3 = match<{ a: { prop: number }[] }>({ a: [] })
464+
.with({ a: P.select(P.array({ prop: P._ })) }, (a) => {
465+
type t = Expect<Equal<typeof a, { prop: number }[]>>;
466+
return { a };
467+
})
468+
.otherwise(() => null);
469+
470+
expect(res3).toEqual({ a: [] });
471+
});
437472
});

0 commit comments

Comments
 (0)