Skip to content

Commit

Permalink
test: add tests for custom key serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikaple committed Mar 22, 2024
1 parent b1c5bb8 commit 9ab90f5
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/flatten.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,34 @@ describe('flattenObject', () => {
testFlatten({ cat }, { cat });
});

it('should be able to custom key serializer', () => {
expect(
flatten(
{ a: [0, { b: [1], c: { d: [2], 5: [6] } }] },
{
serializeFlattenKey(key, prefix, meta) {
if (meta.isArrayIndex) {
return `${prefix}.[${key}]`;
}
if (
meta.hasSpecialCharacters ||
meta.isEmpty ||
/^\d+$/.test(key)
) {
return `${prefix}[${JSON.stringify(key)}]`;
}
return prefix ? `${prefix}.${key}` : key;
},
},
),
).toEqual({
'a.[0]': 0,
'a.[1].b.[0]': 1,
'a.[1].c.d.[0]': 2,
'a.[1].c["5"].[0]': 6,
});
});

it('should not throw on illegal input', () => {
expect(flatten('' as any)).toEqual({});
});
Expand Down

0 comments on commit 9ab90f5

Please sign in to comment.