Skip to content

Commit 19a4e45

Browse files
committed
feat: add undefinedAsNil option to Encoder
1 parent 0e02917 commit 19a4e45

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/Encoder.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ export type EncoderOptions<ContextType = undefined> = Partial<
6161
*/
6262
ignoreUndefined: boolean;
6363

64+
/**
65+
* If `true`, an object property with `undefined` value are encoded as `nil`, same as null.
66+
* e.g. `{ foo: undefined }` will be encoded as `{ foo: nil }`.
67+
* This flag has no effect if `ignoreUndefined` is `true`.
68+
*
69+
* Defaults to `true`.
70+
*/
71+
undefinedAsNil: boolean;
72+
6473
/**
6574
* If `true`, integer numbers are encoded as floating point numbers,
6675
* with the `forceFloat32` option taken into account.
@@ -82,6 +91,7 @@ export class Encoder<ContextType = undefined> {
8291
private readonly forceFloat32: boolean;
8392
private readonly ignoreUndefined: boolean;
8493
private readonly forceIntegerToFloat: boolean;
94+
private readonly undefinedAsNil: boolean;
8595

8696
private pos: number;
8797
private view: DataView;
@@ -99,6 +109,7 @@ export class Encoder<ContextType = undefined> {
99109
this.sortKeys = options?.sortKeys ?? false;
100110
this.forceFloat32 = options?.forceFloat32 ?? false;
101111
this.ignoreUndefined = options?.ignoreUndefined ?? false;
112+
this.undefinedAsNil = options?.undefinedAsNil ?? true;
102113
this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;
103114

104115
this.pos = 0;
@@ -174,7 +185,9 @@ export class Encoder<ContextType = undefined> {
174185
throw new Error(`Too deep objects in depth ${depth}`);
175186
}
176187

177-
if (object == null) {
188+
if (object === null) {
189+
this.encodeNil();
190+
} else if (object === undefined && this.undefinedAsNil) {
178191
this.encodeNil();
179192
} else if (typeof object === "boolean") {
180193
this.encodeBoolean(object);

0 commit comments

Comments
 (0)