utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. * Truncates a string
  13. *
  14. * @api public
  15. */
  16. exports.truncate = function (str, length, chr) {
  17. chr = chr || '…'
  18. return str.length >= length ? str.substr(0, length - chr.length) + chr : str
  19. }
  20. /**
  21. * Copies and merges options with defaults.
  22. *
  23. * @param {Object} defaults
  24. * @param {Object} supplied options
  25. * @return {Object} new (merged) object
  26. */
  27. function options (defaults, opts) {
  28. for (var p in opts) {
  29. if (opts[p] && opts[p].constructor && opts[p].constructor === Object) {
  30. defaults[p] = defaults[p] || {}
  31. options(defaults[p], opts[p])
  32. } else {
  33. defaults[p] = opts[p]
  34. }
  35. }
  36. return defaults
  37. };
  38. exports.options = options
  39. //
  40. // For consideration of terminal "color" programs like colors.js,
  41. // which can add ANSI escape color codes to strings,
  42. // we destyle the ANSI color escape codes for padding calculations.
  43. //
  44. // see: http://en.wikipedia.org/wiki/ANSI_escape_code
  45. //
  46. exports.strlen = function (str) {
  47. var code = /\u001b\[(?:\d*;){0,5}\d*m/g
  48. var stripped = ('' + (str != null ? str : '')).replace(code, '')
  49. var split = stripped.split('\n')
  50. return split.reduce(function (memo, s) { return (s.length > memo) ? s.length : memo }, 0)
  51. }