stringify.js 2.5 KB

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