debug.component.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. ;(function(){
  2. /**
  3. * Create a debugger with the given `name`.
  4. *
  5. * @param {String} name
  6. * @return {Type}
  7. * @api public
  8. */
  9. function debug(name) {
  10. if (!debug.enabled(name)) return function(){};
  11. return function(fmt){
  12. var curr = new Date;
  13. var ms = curr - (debug[name] || curr);
  14. debug[name] = curr;
  15. fmt = name
  16. + ' '
  17. + fmt
  18. + ' +' + debug.humanize(ms);
  19. // This hackery is required for IE8
  20. // where `console.log` doesn't have 'apply'
  21. window.console
  22. && console.log
  23. && Function.prototype.apply.call(console.log, console, arguments);
  24. }
  25. }
  26. /**
  27. * The currently active debug mode names.
  28. */
  29. debug.names = [];
  30. debug.skips = [];
  31. /**
  32. * Enables a debug mode by name. This can include modes
  33. * separated by a colon and wildcards.
  34. *
  35. * @param {String} name
  36. * @api public
  37. */
  38. debug.enable = function(name) {
  39. localStorage.debug = name;
  40. var split = (name || '').split(/[\s,]+/)
  41. , len = split.length;
  42. for (var i = 0; i < len; i++) {
  43. name = split[i].replace('*', '.*?');
  44. if (name[0] === '-') {
  45. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  46. }
  47. else {
  48. debug.names.push(new RegExp('^' + name + '$'));
  49. }
  50. }
  51. };
  52. /**
  53. * Disable debug output.
  54. *
  55. * @api public
  56. */
  57. debug.disable = function(){
  58. debug.enable('');
  59. };
  60. /**
  61. * Humanize the given `ms`.
  62. *
  63. * @param {Number} m
  64. * @return {String}
  65. * @api private
  66. */
  67. debug.humanize = function(ms) {
  68. var sec = 1000
  69. , min = 60 * 1000
  70. , hour = 60 * min;
  71. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  72. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  73. if (ms >= sec) return (ms / sec | 0) + 's';
  74. return ms + 'ms';
  75. };
  76. /**
  77. * Returns true if the given mode name is enabled, false otherwise.
  78. *
  79. * @param {String} name
  80. * @return {Boolean}
  81. * @api public
  82. */
  83. debug.enabled = function(name) {
  84. for (var i = 0, len = debug.skips.length; i < len; i++) {
  85. if (debug.skips[i].test(name)) {
  86. return false;
  87. }
  88. }
  89. for (var i = 0, len = debug.names.length; i < len; i++) {
  90. if (debug.names[i].test(name)) {
  91. return true;
  92. }
  93. }
  94. return false;
  95. };
  96. // persist
  97. if (window.localStorage) debug.enable(localStorage.debug);
  98. module.exports = debug;
  99. })();