utils.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Repeats a string.
  3. *
  4. * @param {String} char(s)
  5. * @param {Number} number of times
  6. * @return {String} repeated string
  7. */
  8. exports.repeat = function (str, times){
  9. return Array(times + 1).join(str);
  10. };
  11. /**
  12. * Pads a string
  13. *
  14. * @api public
  15. */
  16. exports.pad = function (str, len, pad, dir) {
  17. if (len + 1 >= str.length)
  18. switch (dir){
  19. case 'left':
  20. str = Array(len + 1 - str.length).join(pad) + str;
  21. break;
  22. case 'both':
  23. var right = Math.ceil((padlen = len - str.length) / 2);
  24. var left = padlen - right;
  25. str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
  26. break;
  27. default:
  28. str = str + Array(len + 1 - str.length).join(pad);
  29. };
  30. return str;
  31. };
  32. /**
  33. * Truncates a string
  34. *
  35. * @api public
  36. */
  37. exports.truncate = function (str, length, chr){
  38. chr = chr || '…';
  39. return str.length >= length ? str.substr(0, length - chr.length) + chr : str;
  40. };
  41. /**
  42. * Copies and merges options with defaults.
  43. *
  44. * @param {Object} defaults
  45. * @param {Object} supplied options
  46. * @return {Object} new (merged) object
  47. */
  48. function options(defaults, opts) {
  49. for (var p in opts) {
  50. if (opts[p] && opts[p].constructor && opts[p].constructor === Object) {
  51. defaults[p] = defaults[p] || {};
  52. options(defaults[p], opts[p]);
  53. } else {
  54. defaults[p] = opts[p];
  55. }
  56. }
  57. return defaults;
  58. };
  59. exports.options = options;
  60. //
  61. // For consideration of terminal "color" programs like colors.js,
  62. // which can add ANSI escape color codes to strings,
  63. // we destyle the ANSI color escape codes for padding calculations.
  64. //
  65. // see: http://en.wikipedia.org/wiki/ANSI_escape_code
  66. //
  67. exports.strlen = function(str){
  68. var code = /\u001b\[(?:\d*;){0,5}\d*m/g;
  69. var stripped = ("" + str).replace(code,'');
  70. var split = stripped.split("\n");
  71. return split.reduce(function (memo, s) { return (s.length > memo) ? s.length : memo }, 0);
  72. }