@@ -34,6 +34,10 @@ 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+ if ( opts && typeof opts . collapseEmpty !== 'undefined' && typeof opts . collapseEmpty !== 'boolean' ) {
38+ throw new TypeError ( '`collapseEmpty` must be a boolean, if provided' ) ;
39+ }
40+ var collapseEmpty = ! ! opts && opts . collapseEmpty ;
3741
3842 var cmpOpt = typeof opts === 'function' ? opts : opts && opts . cmp ;
3943 /** @type {undefined | (<T extends import('.').NonArrayNode>(node: T) => (a: Exclude<keyof T, symbol | number>, b: Exclude<keyof T, symbol | number>) => number) } */
@@ -66,20 +70,27 @@ module.exports = function stableStringify(obj) {
6670 }
6771
6872 node = replacer ( parent , key , node ) ;
69-
7073 if ( node === undefined ) {
7174 return ;
7275 }
7376 if ( typeof node !== 'object' || node === null ) {
7477 return jsonStringify ( node ) ;
7578 }
79+
80+ /** @type {(out: string[], brackets: '[]' | '{}') => string } */
81+ var groupOutput = function ( out , brackets ) {
82+ return collapseEmpty && out . length === 0
83+ ? brackets
84+ : ( brackets === '[]' ? '[' : '{' ) + $join ( out , ',' ) + indent + ( brackets === '[]' ? ']' : '}' ) ;
85+ } ;
86+
7687 if ( isArray ( node ) ) {
7788 var out = [ ] ;
7889 for ( var i = 0 ; i < node . length ; i ++ ) {
7990 var item = stringify ( node , i , node [ i ] , level + 1 ) || jsonStringify ( null ) ;
8091 out [ out . length ] = indent + space + item ;
8192 }
82- return '[' + $join ( out , ',' ) + indent + ']' ;
93+ return groupOutput ( out , '[]' ) ;
8394 }
8495
8596 if ( $indexOf ( seen , node ) !== - 1 ) {
@@ -107,7 +118,7 @@ module.exports = function stableStringify(obj) {
107118 out [ out . length ] = indent + space + keyValue ;
108119 }
109120 $splice ( seen , $indexOf ( seen , node ) , 1 ) ;
110- return '{' + $join ( out , ',' ) + indent + '}' ;
121+ return groupOutput ( out , '{}' ) ;
111122 } ( { '' : obj } , '' , obj , 0 )
112123 ) ;
113124} ;
0 commit comments