10
10
import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol' ;
11
11
12
12
const MAX_ARRAY_LENGTH = 10 ;
13
+ const MAX_RECURSIVE_DEPTH = 2 ;
13
14
14
15
/**
15
16
* Used to print values in error messages.
16
17
*/
17
18
export default function inspect ( value : mixed ) : string {
18
- return formatValue ( value ) ;
19
+ return formatValue ( value , 0 ) ;
19
20
}
20
21
21
- function formatValue ( value ) {
22
+ function formatValue ( value , recurseTimes ) {
22
23
switch ( typeof value ) {
23
24
case 'string' :
24
25
return JSON . stringify ( value ) ;
@@ -33,12 +34,12 @@ function formatValue(value) {
33
34
const customValue = customInspectFn . call ( value ) ;
34
35
return typeof customValue === 'string'
35
36
? customValue
36
- : formatValue ( customValue ) ;
37
+ : formatValue ( customValue , recurseTimes ) ;
37
38
} else if ( Array . isArray ( value ) ) {
38
- return formatArray ( value ) ;
39
+ return formatArray ( value , recurseTimes ) ;
39
40
}
40
41
41
- return formatObject ( value ) ;
42
+ return formatObject ( value , recurseTimes ) ;
42
43
}
43
44
44
45
return String ( value ) ;
@@ -47,31 +48,39 @@ function formatValue(value) {
47
48
}
48
49
}
49
50
50
- function formatObject ( object ) {
51
+ function formatObject ( object , recurseTimes ) {
51
52
const keys = Object . keys ( object ) ;
52
53
if ( keys . length === 0 ) {
53
54
return '{}' ;
54
55
}
55
56
57
+ if ( recurseTimes === MAX_RECURSIVE_DEPTH ) {
58
+ return '[' + getObjectTag ( object ) + ']' ;
59
+ }
60
+
56
61
const properties = keys . map ( key => {
57
- const value = formatValue ( object [ key ] ) ;
62
+ const value = formatValue ( object [ key ] , recurseTimes + 1 ) ;
58
63
return key + ': ' + value ;
59
64
} ) ;
60
65
61
66
return '{ ' + properties . join ( ', ' ) + ' }' ;
62
67
}
63
68
64
- function formatArray ( array ) {
69
+ function formatArray ( array , recurseTimes ) {
65
70
if ( array . length === 0 ) {
66
71
return '[]' ;
67
72
}
68
73
74
+ if ( recurseTimes === MAX_RECURSIVE_DEPTH ) {
75
+ return '[Array]' ;
76
+ }
77
+
69
78
const len = Math . min ( MAX_ARRAY_LENGTH , array . length ) ;
70
79
const remaining = array . length - len ;
71
80
const items = [ ] ;
72
81
73
82
for ( let i = 0 ; i < len ; ++ i ) {
74
- items . push ( formatValue ( array [ i ] ) ) ;
83
+ items . push ( formatValue ( array [ i ] , recurseTimes + 1 ) ) ;
75
84
}
76
85
77
86
if ( remaining === 1 ) {
@@ -94,3 +103,19 @@ function getCustomFn(object) {
94
103
return object . inspect ;
95
104
}
96
105
}
106
+
107
+ function getObjectTag ( object ) {
108
+ const tag = Object . prototype . toString
109
+ . call ( object )
110
+ . replace ( / ^ \[ o b j e c t / , '' )
111
+ . replace ( / ] $ / , '' ) ;
112
+
113
+ if ( tag === 'Object' && typeof object . constructor === 'function' ) {
114
+ const name = object . constructor . name ;
115
+ if ( typeof name === 'string' ) {
116
+ return name ;
117
+ }
118
+ }
119
+
120
+ return tag ;
121
+ }
0 commit comments