File: dump_js_dump.js - YUI Library
Version 3.17.2
Show:

File: dump/js/dump.js

  1. /**
  2. * Returns a simple string representation of the object or array.
  3. * Other types of objects will be returned unprocessed. Arrays
  4. * are expected to be indexed. Use object notation for
  5. * associative arrays.
  6. *
  7. * If included, the dump method is added to the YUI instance.
  8. *
  9. * @module dump
  10. */
  11.  
  12. var L = Y.Lang,
  13. OBJ = '{...}',
  14. FUN = 'f(){...}',
  15. COMMA = ', ',
  16. ARROW = ' => ',
  17.  
  18. /**
  19. * Returns a simple string representation of the object or array.
  20. * Other types of objects will be returned unprocessed. Arrays
  21. * are expected to be indexed.
  22. *
  23. * @method dump
  24. * @param {Object} o The object to dump.
  25. * @param {Number} d How deep to recurse child objects, default 3.
  26. * @return {String} the dump result.
  27. * @for YUI
  28. */
  29. dump = function(o, d) {
  30. var i, len, s = [], type = L.type(o);
  31.  
  32. // Cast non-objects to string
  33. // Skip dates because the std toString is what we want
  34. // Skip HTMLElement-like objects because trying to dump
  35. // an element will cause an unhandled exception in FF 2.x
  36. if (!L.isObject(o)) {
  37. return o + '';
  38. } else if (type == 'date') {
  39. return o;
  40. } else if (o.nodeType && o.tagName) {
  41. return o.tagName + '#' + o.id;
  42. } else if (o.document && o.navigator) {
  43. return 'window';
  44. } else if (o.location && o.body) {
  45. return 'document';
  46. } else if (type == 'function') {
  47. return FUN;
  48. }
  49.  
  50. // dig into child objects the depth specifed. Default 3
  51. d = (L.isNumber(d)) ? d : 3;
  52.  
  53. // arrays [1, 2, 3]
  54. if (type == 'array') {
  55. s.push('[');
  56. for (i = 0, len = o.length; i < len; i = i + 1) {
  57. if (L.isObject(o[i])) {
  58. s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
  59. } else {
  60. s.push(o[i]);
  61. }
  62. s.push(COMMA);
  63. }
  64. if (s.length > 1) {
  65. s.pop();
  66. }
  67. s.push(']');
  68. // regexp /foo/
  69. } else if (type == 'regexp') {
  70. s.push(o.toString());
  71. // objects {k1 => v1, k2 => v2}
  72. } else {
  73. s.push('{');
  74. for (i in o) {
  75. if (o.hasOwnProperty(i)) {
  76. try {
  77. s.push(i + ARROW);
  78. if (L.isObject(o[i])) {
  79. s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
  80. } else {
  81. s.push(o[i]);
  82. }
  83. s.push(COMMA);
  84. } catch (e) {
  85. s.push('Error: ' + e.message);
  86. }
  87. }
  88. }
  89. if (s.length > 1) {
  90. s.pop();
  91. }
  92. s.push('}');
  93. }
  94.  
  95. return s.join('');
  96. };
  97.  
  98. Y.dump = dump;
  99. L.dump = dump;
  100.  
  101.