@@ -34,6 +34,7 @@ module.exports = function stableStringify(obj) {
3434 var cycles = ! ! opts && typeof opts . cycles === 'boolean' && opts . cycles ;
3535 /** @type {undefined | typeof defaultReplacer } */
3636 var replacer = opts && opts . replacer ? callBind ( opts . replacer ) : defaultReplacer ;
37+ var collapseEmpty = ( opts && opts . collapseEmpty ) || false ;
3738
3839 var cmpOpt = typeof opts === 'function' ? opts : opts && opts . cmp ;
3940 /** @type {undefined | (<T extends import('.').NonArrayNode>(node: T) => (a: Exclude<keyof T, symbol | number>, b: Exclude<keyof T, symbol | number>) => number) } */
@@ -73,13 +74,21 @@ module.exports = function stableStringify(obj) {
7374 if ( typeof node !== 'object' || node === null ) {
7475 return jsonStringify ( node ) ;
7576 }
77+
78+ /** @type {(out: any[], brackets: '[]' | '{}') => string } */
79+ var groupOutput = function ( out , brackets ) {
80+ return collapseEmpty && out . length === 0
81+ ? brackets
82+ : brackets [ 0 ] + $join ( out , ',' ) + indent + brackets [ 1 ] ;
83+ } ;
84+
7685 if ( isArray ( node ) ) {
7786 var out = [ ] ;
7887 for ( var i = 0 ; i < node . length ; i ++ ) {
7988 var item = stringify ( node , i , node [ i ] , level + 1 ) || jsonStringify ( null ) ;
8089 out [ out . length ] = indent + space + item ;
8190 }
82- return '[' + $join ( out , ',' ) + indent + ']' ;
91+ return groupOutput ( out , '[]' ) ;
8392 }
8493
8594 if ( $indexOf ( seen , node ) !== - 1 ) {
@@ -107,7 +116,7 @@ module.exports = function stableStringify(obj) {
107116 out [ out . length ] = indent + space + keyValue ;
108117 }
109118 $splice ( seen , $indexOf ( seen , node ) , 1 ) ;
110- return '{' + $join ( out , ',' ) + indent + '}' ;
119+ return groupOutput ( out , '{}' ) ;
111120 } ( { '' : obj } , '' , obj , 0 )
112121 ) ;
113122} ;
0 commit comments