UNPKG

2.37 kBJavaScriptView Raw
1var serialize = require('dom-serialize')
2var instanceOf = require('./util').instanceOf
3
4function isNode (obj) {
5 return (obj.tagName || obj.nodeName) && obj.nodeType
6}
7
8function stringify (obj, depth) {
9 if (depth === 0) {
10 return '...'
11 }
12
13 if (obj === null) {
14 return 'null'
15 }
16
17 switch (typeof obj) {
18 case 'symbol':
19 return obj.toString()
20 case 'string':
21 return "'" + obj + "'"
22 case 'undefined':
23 return 'undefined'
24 case 'function':
25 try {
26 // function abc(a, b, c) { /* code goes here */ }
27 // -> function abc(a, b, c) { ... }
28 return obj.toString().replace(/\{[\s\S]*\}/, '{ ... }')
29 } catch (err) {
30 if (err instanceof TypeError) {
31 // Support older browsers
32 return 'function ' + (obj.name || '') + '() { ... }'
33 } else {
34 throw err
35 }
36 }
37 case 'boolean':
38 return obj ? 'true' : 'false'
39 case 'object':
40 var strs = []
41 if (instanceOf(obj, 'Array')) {
42 strs.push('[')
43 for (var i = 0, ii = obj.length; i < ii; i++) {
44 if (i) {
45 strs.push(', ')
46 }
47 strs.push(stringify(obj[i], depth - 1))
48 }
49 strs.push(']')
50 } else if (instanceOf(obj, 'Date')) {
51 return obj.toString()
52 } else if (instanceOf(obj, 'Text')) {
53 return obj.nodeValue
54 } else if (instanceOf(obj, 'Comment')) {
55 return '<!--' + obj.nodeValue + '-->'
56 } else if (obj.outerHTML) {
57 return obj.outerHTML
58 } else if (isNode(obj)) {
59 return serialize(obj)
60 } else if (instanceOf(obj, 'Error')) {
61 return obj.toString() + '\n' + obj.stack
62 } else {
63 var constructor = 'Object'
64 if (obj.constructor && typeof obj.constructor === 'function') {
65 constructor = obj.constructor.name
66 }
67
68 strs.push(constructor)
69 strs.push('{')
70 var first = true
71 for (var key in obj) {
72 if (Object.prototype.hasOwnProperty.call(obj, key)) {
73 if (first) {
74 first = false
75 } else {
76 strs.push(', ')
77 }
78
79 strs.push(key + ': ' + stringify(obj[key], depth - 1))
80 }
81 }
82 strs.push('}')
83 }
84 return strs.join('')
85 default:
86 return obj
87 }
88}
89
90module.exports = stringify