progress-bar.js 998 B

1234567891011121314151617181920212223242526272829303132333435
  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) completed = 0
  9. if (completed > 1) completed = 1
  10. if (width <= 0) return ''
  11. var sofar = Math.round(width * completed)
  12. var rest = width - sofar
  13. var template = [
  14. {type: 'complete', value: repeat(theme.complete, sofar), length: sofar},
  15. {type: 'remaining', value: repeat(theme.remaining, rest), length: rest}
  16. ]
  17. return renderTemplate(width, template, theme)
  18. }
  19. // lodash's way of repeating
  20. function repeat (string, width) {
  21. var result = ''
  22. var n = width
  23. do {
  24. if (n % 2) {
  25. result += string
  26. }
  27. n = Math.floor(n / 2)
  28. /*eslint no-self-assign: 0*/
  29. string += string
  30. } while (n && stringWidth(result) < width)
  31. return wideTruncate(result, width)
  32. }