index.js 649 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const stripAnsi = require('strip-ansi');
  3. const isFullwidthCodePoint = require('is-fullwidth-code-point');
  4. module.exports = str => {
  5. if (typeof str !== 'string' || str.length === 0) {
  6. return 0;
  7. }
  8. str = stripAnsi(str);
  9. let width = 0;
  10. for (let i = 0; i < str.length; i++) {
  11. const code = str.codePointAt(i);
  12. // Ignore control characters
  13. if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
  14. continue;
  15. }
  16. // Ignore combining characters
  17. if (code >= 0x300 && code <= 0x36F) {
  18. continue;
  19. }
  20. // Surrogates
  21. if (code > 0xFFFF) {
  22. i++;
  23. }
  24. width += isFullwidthCodePoint(code) ? 2 : 1;
  25. }
  26. return width;
  27. };