@@ -17,6 +17,7 @@ export class Encoder {
1717 readonly extensionCodec = ExtensionCodec . defaultCodec ,
1818 readonly maxDepth = DEFAULT_MAX_DEPTH ,
1919 readonly initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE ,
20+ readonly sortKeys = false ,
2021 ) { }
2122
2223 encode ( object : unknown , depth : number ) : void {
@@ -223,18 +224,12 @@ export class Encoder {
223224 }
224225 }
225226
226- countObjectKeys ( object : Record < string , unknown > ) : number {
227- let count = 0 ;
228- for ( const key in object ) {
229- if ( Object . prototype . hasOwnProperty . call ( object , key ) ) {
230- count ++ ;
231- }
232- }
233- return count ;
234- }
235-
236227 encodeMap ( object : Record < string , unknown > , depth : number ) {
237- const size = this . countObjectKeys ( object ) ;
228+ const keys = Object . keys ( object ) ;
229+ if ( this . sortKeys ) {
230+ keys . sort ( ) ;
231+ }
232+ const size = keys . length ;
238233 if ( size < 16 ) {
239234 // fixmap
240235 this . writeU8 ( 0x80 + size ) ;
@@ -249,11 +244,11 @@ export class Encoder {
249244 } else {
250245 throw new Error ( `Too large map object: ${ size } ` ) ;
251246 }
252- for ( const key in object ) {
253- if ( Object . prototype . hasOwnProperty . call ( object , key ) ) {
254- this . encodeString ( key ) ;
255- this . encode ( object [ key ] , depth + 1 ) ;
256- }
247+
248+ for ( let i = 0 ; i < size ; i ++ ) {
249+ const key = keys [ i ] ;
250+ this . encodeString ( key ) ;
251+ this . encode ( object [ key ] , depth + 1 ) ;
257252 }
258253 }
259254
0 commit comments