@@ -19,6 +19,7 @@ export class Encoder<ContextType> {
1919 readonly initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE ,
2020 readonly sortKeys = false ,
2121 readonly forceFloat32 = false ,
22+ readonly ignoreUndefined = false ,
2223 ) { }
2324
2425 encode ( object : unknown , depth : number ) : void {
@@ -231,12 +232,26 @@ export class Encoder<ContextType> {
231232 }
232233 }
233234
235+ countWithoutUndefined ( object : Record < string , unknown > , keys : ReadonlyArray < string > ) : number {
236+ let count = 0 ;
237+
238+ for ( const key of keys ) {
239+ if ( object [ key ] !== undefined ) {
240+ count ++ ;
241+ }
242+ }
243+
244+ return count ;
245+ }
246+
234247 encodeMap ( object : Record < string , unknown > , depth : number ) {
235248 const keys = Object . keys ( object ) ;
236249 if ( this . sortKeys ) {
237250 keys . sort ( ) ;
238251 }
239- const size = keys . length ;
252+
253+ const size = this . ignoreUndefined ? this . countWithoutUndefined ( object , keys ) : keys . length ;
254+
240255 if ( size < 16 ) {
241256 // fixmap
242257 this . writeU8 ( 0x80 + size ) ;
@@ -252,10 +267,13 @@ export class Encoder<ContextType> {
252267 throw new Error ( `Too large map object: ${ size } ` ) ;
253268 }
254269
255- for ( let i = 0 ; i < size ; i ++ ) {
256- const key = keys [ i ] ;
257- this . encodeString ( key ) ;
258- this . encode ( object [ key ] , depth + 1 ) ;
270+ for ( const key of keys ) {
271+ const value = object [ key ] ;
272+
273+ if ( ! ( this . ignoreUndefined && value === undefined ) ) {
274+ this . encodeString ( key ) ;
275+ this . encode ( value , depth + 1 ) ;
276+ }
259277 }
260278 }
261279
0 commit comments