align.js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict'
  2. var stringWidth = require('string-width')
  3. exports.center = alignCenter
  4. exports.left = alignLeft
  5. exports.right = alignRight
  6. // lodash's way of generating pad characters.
  7. function createPadding (width) {
  8. var result = ''
  9. var string = ' '
  10. var n = width
  11. do {
  12. if (n % 2) {
  13. result += string;
  14. }
  15. n = Math.floor(n / 2);
  16. string += string;
  17. } while (n);
  18. return result;
  19. }
  20. function alignLeft (str, width) {
  21. var trimmed = str.trimRight()
  22. if (trimmed.length === 0 && str.length >= width) return str
  23. var padding = ''
  24. var strWidth = stringWidth(trimmed)
  25. if (strWidth < width) {
  26. padding = createPadding(width - strWidth)
  27. }
  28. return trimmed + padding
  29. }
  30. function alignRight (str, width) {
  31. var trimmed = str.trimLeft()
  32. if (trimmed.length === 0 && str.length >= width) return str
  33. var padding = ''
  34. var strWidth = stringWidth(trimmed)
  35. if (strWidth < width) {
  36. padding = createPadding(width - strWidth)
  37. }
  38. return padding + trimmed
  39. }
  40. function alignCenter (str, width) {
  41. var trimmed = str.trim()
  42. if (trimmed.length === 0 && str.length >= width) return str
  43. var padLeft = ''
  44. var padRight = ''
  45. var strWidth = stringWidth(trimmed)
  46. if (strWidth < width) {
  47. var padLeftBy = parseInt((width - strWidth) / 2, 10)
  48. padLeft = createPadding(padLeftBy)
  49. padRight = createPadding(width - (strWidth + padLeftBy))
  50. }
  51. return padLeft + trimmed + padRight
  52. }