forked from rhinofi/logger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringify.js
More file actions
44 lines (42 loc) · 1.26 KB
/
Copy pathstringify.js
File metadata and controls
44 lines (42 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const escapeString = str => str && str.replace(/[\n\r]/g, '')
// Won't work for minified class names however we need something fast
// That does not require iterating through everything
const fetchTypeName = data => data && data.constructor && data.constructor.name
const stringify = (data, depth = 5, customFormatters = {}) => {
const typename = fetchTypeName(data)
/* eslint-disable no-nested-ternary */
return data === undefined
? 'null'
: !data
? JSON.stringify(data)
: typeof data === 'object' && !Array.isArray(data)
? customFormatters[typename]
? customFormatters[typename](data)
: typeof data.toJSON === 'function'
? stringify(data.toJSON(), depth)
: depth < 1
? '"{ ? }"'
: `{${
Object
.keys(data)
.map(
k => `${stringify(k, depth - 1)}: ${stringify(data[k], depth - 1)}`,
)
.join(', ')
}}`
: Array.isArray(data)
? `[${
data
.map(d => (depth < 1 ? '"?"' : stringify(d, depth - 1)))
.join(', ')
}]`
: typeof data === 'function'
? '"f()"'
: JSON.stringify(data)
}
const stringifySimple = data => (
typeof data === 'string'
? escapeString(data)
: data
)
module.exports = { stringify, stringifySimple }