Skip to content

Commit

Permalink
fix: support empty Map and Set (jacob-ebey#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
caprica committed May 8, 2024
1 parent a72f7a7 commit 8ba3587
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/flatten.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,21 @@ function stringify(this: ThisEncode, input: unknown, index: number) {
input.source
)},${JSON.stringify(input.flags)}]`;
} else if (input instanceof Set) {
str[index] = `["${TYPE_SET}",${[...input]
.map((val) => flatten.call(this, val))
.join(",")}]`;
if (input.size > 0) {
str[index] = `["${TYPE_SET}",${[...input]
.map((val) => flatten.call(this, val))
.join(",")}]`;
} else {
str[index] = `["${TYPE_SET}"]`;
}
} else if (input instanceof Map) {
str[index] = `["${TYPE_MAP}",${[...input]
.flatMap(([k, v]) => [flatten.call(this, k), flatten.call(this, v)])
.join(",")}]`;
if (input.size > 0) {
str[index] = `["${TYPE_MAP}",${[...input]
.flatMap(([k, v]) => [flatten.call(this, k), flatten.call(this, v)])
.join(",")}]`;
} else {
str[index] = `["${TYPE_MAP}"]`;
}
} else if (input instanceof Promise) {
str[index] = `["${TYPE_PROMISE}",${index}]`;
deferred[index] = input;
Expand Down
12 changes: 12 additions & 0 deletions src/turbo-stream.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,24 @@ test("should encode and decode Map", async () => {
expect(output).toEqual(input);
});

test("should encode and decode empty Map", async () => {
const input = new Map()
const output = await quickDecode(encode(input));
expect(output).toEqual(input);
});

test("should encode and decode Set", async () => {
const input = new Set(["foo", "bar"]);
const output = await quickDecode(encode(input));
expect(output).toEqual(input);
});

test("should encode and decode empty Set", async () => {
const input = new Set();
const output = await quickDecode(encode(input));
expect(output).toEqual(input);
});

test("should encode and decode an Error", async () => {
const input = new Error("foo");
const output = await quickDecode(encode(input));
Expand Down

0 comments on commit 8ba3587

Please sign in to comment.