stringify.js
1.87 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var serialize = require('dom-serialize')
var instanceOf = require('./util').instanceOf
var isNode = function (obj) {
return (obj.tagName || obj.nodeName) && obj.nodeType
}
var stringify = function stringify (obj, depth) {
if (depth === 0) {
return '...'
}
if (obj === null) {
return 'null'
}
switch (typeof obj) {
case 'string':
return "'" + obj + "'"
case 'undefined':
return 'undefined'
case 'function':
return obj.toString().replace(/\{[\s\S]*\}/, '{ ... }')
case 'boolean':
return obj ? 'true' : 'false'
case 'object':
var strs = []
if (instanceOf(obj, 'Array')) {
strs.push('[')
for (var i = 0, ii = obj.length; i < ii; i++) {
if (i) {
strs.push(', ')
}
strs.push(stringify(obj[i], depth - 1))
}
strs.push(']')
} else if (instanceOf(obj, 'Date')) {
return obj.toString()
} else if (instanceOf(obj, 'Text')) {
return obj.nodeValue
} else if (instanceOf(obj, 'Comment')) {
return '<!--' + obj.nodeValue + '-->'
} else if (obj.outerHTML) {
return obj.outerHTML
} else if (isNode(obj)) {
return serialize(obj)
} else {
var constructor = 'Object'
if (obj.constructor && typeof obj.constructor === 'function') {
constructor = obj.constructor.name
}
strs.push(constructor)
strs.push('{')
var first = true
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (first) {
first = false
} else {
strs.push(', ')
}
strs.push(key + ': ' + stringify(obj[key], depth - 1))
}
}
strs.push('}')
}
return strs.join('')
default:
return obj
}
}
module.exports = stringify