@@ -34,6 +34,10 @@ module.exports = function stableStringify(obj) {
34
34
var cycles = ! ! opts && typeof opts . cycles === 'boolean' && opts . cycles ;
35
35
/** @type {undefined | typeof defaultReplacer } */
36
36
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 ;
37
41
38
42
var cmpOpt = typeof opts === 'function' ? opts : opts && opts . cmp ;
39
43
/** @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) {
66
70
}
67
71
68
72
node = replacer ( parent , key , node ) ;
69
-
70
73
if ( node === undefined ) {
71
74
return ;
72
75
}
73
76
if ( typeof node !== 'object' || node === null ) {
74
77
return jsonStringify ( node ) ;
75
78
}
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
+
76
87
if ( isArray ( node ) ) {
77
88
var out = [ ] ;
78
89
for ( var i = 0 ; i < node . length ; i ++ ) {
79
90
var item = stringify ( node , i , node [ i ] , level + 1 ) || jsonStringify ( null ) ;
80
91
out [ out . length ] = indent + space + item ;
81
92
}
82
- return '[' + $join ( out , ',' ) + indent + ']' ;
93
+ return groupOutput ( out , '[]' ) ;
83
94
}
84
95
85
96
if ( $indexOf ( seen , node ) !== - 1 ) {
@@ -107,7 +118,7 @@ module.exports = function stableStringify(obj) {
107
118
out [ out . length ] = indent + space + keyValue ;
108
119
}
109
120
$splice ( seen , $indexOf ( seen , node ) , 1 ) ;
110
- return '{' + $join ( out , ',' ) + indent + '}' ;
121
+ return groupOutput ( out , '{}' ) ;
111
122
} ( { '' : obj } , '' , obj , 0 )
112
123
) ;
113
124
} ;
0 commit comments