index.js 741 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var stripAnsi = require('strip-ansi');
  3. var codePointAt = require('code-point-at');
  4. var isFullwidthCodePoint = require('is-fullwidth-code-point');
  5. // https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1345
  6. module.exports = function (str) {
  7. if (typeof str !== 'string' || str.length === 0) {
  8. return 0;
  9. }
  10. var width = 0;
  11. str = stripAnsi(str);
  12. for (var i = 0; i < str.length; i++) {
  13. var code = codePointAt(str, i);
  14. // ignore control characters
  15. if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
  16. continue;
  17. }
  18. // surrogates
  19. if (code >= 0x10000) {
  20. i++;
  21. }
  22. if (isFullwidthCodePoint(code)) {
  23. width += 2;
  24. } else {
  25. width++;
  26. }
  27. }
  28. return width;
  29. };