progress-bar.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict'
  2. var validate = require('aproba')
  3. var renderTemplate = require('./render-template.js')
  4. var wideTruncate = require('./wide-truncate')
  5. var stringWidth = require('string-width')
  6. module.exports = function (theme, width, completed) {
  7. validate('ONN', [theme, width, completed])
  8. if (completed < 0) {
  9. completed = 0
  10. }
  11. if (completed > 1) {
  12. completed = 1
  13. }
  14. if (width <= 0) {
  15. return ''
  16. }
  17. var sofar = Math.round(width * completed)
  18. var rest = width - sofar
  19. var template = [
  20. { type: 'complete', value: repeat(theme.complete, sofar), length: sofar },
  21. { type: 'remaining', value: repeat(theme.remaining, rest), length: rest },
  22. ]
  23. return renderTemplate(width, template, theme)
  24. }
  25. // lodash's way of repeating
  26. function repeat (string, width) {
  27. var result = ''
  28. var n = width
  29. do {
  30. if (n % 2) {
  31. result += string
  32. }
  33. n = Math.floor(n / 2)
  34. /* eslint no-self-assign: 0 */
  35. string += string
  36. } while (n && stringWidth(result) < width)
  37. return wideTruncate(result, width)
  38. }