Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: preserve entry order when encoding Set and Map #54

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/turbo-stream.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ test("should encode and decode Map", async () => {
expect(output).toEqual(input);
});

test("should preserve Map entry order", async () => {
const input = new Map([
["foo", "bar"],
["baz", "qux"],
]);
const output = await quickDecode(encode(input));
expect([...output as Map<unknown, unknown>]).toEqual([...input])
})

test("should encode and decode empty Map", async () => {
const input = new Map();
const output = await quickDecode(encode(input));
Expand All @@ -132,6 +141,12 @@ test("should encode and decode Set", async () => {
expect(output).toEqual(input);
});

test("should preserve Set entry order", async () => {
const input = new Set(["foo", "bar"]);
const output = await quickDecode(encode(input));
expect([...output as Set<unknown>]).toEqual([...input]);
})

test("should encode and decode empty Set", async () => {
const input = new Set();
const output = await quickDecode(encode(input));
Expand Down
12 changes: 10 additions & 2 deletions src/unflatten.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,11 @@ function hydrate(this: ThisDecode, index: number): any {
case TYPE_SET:
const newSet = new Set();
hydrated[index] = newSet;
for (let i = 1; i < value.length; i++)
// Going through the entries from back to front, because the postRun
// callbacks run in reverse (from last item to first)
// This results in a Set with its item order mirrored if we visit the
// first item first.
for (let i = value.length - 1; i >= 1; i --)
stack.push([
value[i],
(v) => {
Expand All @@ -129,7 +133,11 @@ function hydrate(this: ThisDecode, index: number): any {
case TYPE_MAP:
const map = new Map();
hydrated[index] = map;
for (let i = 1; i < value.length; i += 2) {
// Going through the entries from back to front, because the postRun
// callbacks run in reverse (from last item to first)
// This results in a Map with its item order mirrored if we visit the
// first item first.
for (let i = value.length - 2; i >= 1; i -= 2) {
const r: any[] = [];
stack.push([
value[i + 1],
Expand Down