index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var sliceAnsi = require('slice-ansi');
  3. var stringWidth = require('string-width');
  4. module.exports = function (input, columns, options) {
  5. options = options || {};
  6. var position = options.position || 'end';
  7. var ellipsis = '…';
  8. if (typeof input !== 'string') {
  9. throw new TypeError('Expected `input` to be a string, got ' + typeof input);
  10. }
  11. if (typeof columns !== 'number') {
  12. throw new TypeError('Expected `columns` to be a number, got ' + typeof columns);
  13. }
  14. if (columns < 1) {
  15. return '';
  16. }
  17. if (columns === 1) {
  18. return ellipsis;
  19. }
  20. var length = stringWidth(input);
  21. if (length <= columns) {
  22. return input;
  23. }
  24. if (position === 'start') {
  25. return ellipsis + sliceAnsi(input, length - columns + 1, length);
  26. } else if (position === 'middle') {
  27. var half = Math.floor(columns / 2);
  28. return sliceAnsi(input, 0, half) + ellipsis + sliceAnsi(input, length - (columns - half) + 1, length);
  29. } else if (position === 'end') {
  30. return sliceAnsi(input, 0, columns - 1) + ellipsis;
  31. }
  32. throw new Error('Expected `options.position` to be either `start`, `middle` or `end`, got ' + position);
  33. };