utils.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*!
  2. * Cluster - utils
  3. * Copyright (c) 2011 LearnBoost <dev@learnboost.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Frame the given `obj`.
  8. *
  9. * @param {Object} obj
  10. * @return {String}
  11. * @api private
  12. */
  13. exports.frame = function(obj){
  14. return JSON.stringify(obj) + '\n';
  15. };
  16. /**
  17. * Fast alternative to `Array.prototype.slice.call()`.
  18. *
  19. * @param {Arguments} args
  20. * @param {Number} index
  21. * @return {Array}
  22. * @api private
  23. */
  24. exports.toArray = function(args, index){
  25. var arr = []
  26. , len = args.length;
  27. for (var i = (index || 0); i < len; ++i) {
  28. arr.push(args[i]);
  29. }
  30. return arr;
  31. };
  32. /**
  33. * Format byte-size.
  34. *
  35. * @param {Number} bytes
  36. * @return {String}
  37. * @api private
  38. */
  39. exports.formatBytes = function(bytes) {
  40. var kb = 1024
  41. , mb = 1024 * kb
  42. , gb = 1024 * mb;
  43. if (bytes < kb) return bytes + 'b';
  44. if (bytes < mb) return (bytes / kb).toFixed(2) + 'kb';
  45. if (bytes < gb) return (bytes / mb).toFixed(2) + 'mb';
  46. return (bytes / gb).toFixed(2) + 'gb';
  47. };
  48. /**
  49. * Format date difference between `a` and `b`.
  50. *
  51. * @param {Date} a
  52. * @param {Date} b
  53. * @return {String}
  54. * @api private
  55. */
  56. exports.formatDateRange = function(a, b) {
  57. var diff = a > b ? a - b : b - a
  58. , second = 1000
  59. , minute = second * 60
  60. , hour = minute * 60
  61. , day = hour * 24;
  62. function unit(name, n) {
  63. return n + ' ' + name + (1 == n ? '' : 's');
  64. }
  65. if (diff < second) return unit('millisecond', diff);
  66. if (diff < minute) return unit('second', (diff / second).toFixed(0));
  67. if (diff < hour) return unit('minute', (diff / minute).toFixed(0));
  68. if (diff < day) return unit('hour', (diff / hour).toFixed(0));
  69. return unit('day', (diff / day).toFixed(1));
  70. };
  71. /**
  72. * Unshift a callback.
  73. *
  74. * @param {Object} obj
  75. * @param {String} event
  76. * @param {String} fn
  77. * @api private
  78. */
  79. exports.unshiftListener = function(obj, event, fn){
  80. if (Array.isArray(obj._events[event])) {
  81. obj._events[event].unshift(fn);
  82. } else {
  83. obj._events[event] = [fn, obj._events[event]];
  84. }
  85. };