Skip to content
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
49 changes: 26 additions & 23 deletions src/Encoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,26 +392,7 @@ export class Encoder<ContextType = undefined> {
}
}

private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {
let count = 0;

for (const key of keys) {
if (object[key] !== undefined) {
count++;
}
}

return count;
}

private encodeMap(object: Record<string, unknown>, depth: number) {
const keys = Object.keys(object);
if (this.sortKeys) {
keys.sort();
}

const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;

private writeMapHeader(size: number) {
if (size < 16) {
// fixmap
this.writeU8(0x80 + size);
Expand All @@ -426,14 +407,36 @@ export class Encoder<ContextType = undefined> {
} else {
throw new Error(`Too large map object: ${size}`);
}
}

private encodeMap(object: Record<string, unknown>, depth: number) {
const keys = Object.keys(object);
if (this.sortKeys) {
keys.sort();
}

for (const key of keys) {
const value = object[key];
if (this.ignoreUndefined) {
// Each property is read once, so that the size in the header matches the
// entries even if a getter returns a different value on each read.
const entries: Array<[string, unknown]> = [];
for (const key of keys) {
const value = object[key];
if (value !== undefined) {
entries.push([key, value]);
}
}

if (!(this.ignoreUndefined && value === undefined)) {
this.writeMapHeader(entries.length);
for (const [key, value] of entries) {
this.encodeString(key);
this.doEncode(value, depth + 1);
}
} else {
this.writeMapHeader(keys.length);
for (const key of keys) {
this.encodeString(key);
this.doEncode(object[key], depth + 1);
}
}
}

Expand Down
13 changes: 13 additions & 0 deletions test/encode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ describe("encode", () => {
it("encodes { foo: undefined } to {} with `ignoreUndefined: true`", () => {
assert.deepStrictEqual(decode(encode({ foo: undefined, bar: 42 }, { ignoreUndefined: true })), { bar: 42 });
});

it("reads each property once with `ignoreUndefined: true`", () => {
let reads = 0;
const object = {
get foo() {
reads++;
return reads === 1 ? "bar" : undefined;
},
};
const encoded = encode(object, { ignoreUndefined: true });
assert.strictEqual(reads, 1);
assert.deepStrictEqual(decode(encoded), { foo: "bar" });
});
});

context("ArrayBuffer as buffer", () => {
Expand Down