stringify.js 2.3 KB

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