printable-characters.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. const ansiEscapeCode = '[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]'
  3. , zeroWidthCharacterExceptNewline = '\u0000-\u0008\u000B-\u0019\u001b\u009b\u00ad\u200b\u2028\u2029\ufeff\ufe00-\ufe0f'
  4. , zeroWidthCharacter = '\n' + zeroWidthCharacterExceptNewline
  5. , zeroWidthCharactersExceptNewline = new RegExp ('(?:' + ansiEscapeCode + ')|[' + zeroWidthCharacterExceptNewline + ']', 'g')
  6. , zeroWidthCharacters = new RegExp ('(?:' + ansiEscapeCode + ')|[' + zeroWidthCharacter + ']', 'g')
  7. , partition = new RegExp ('((?:' + ansiEscapeCode + ')|[\t' + zeroWidthCharacter + '])?([^\t' + zeroWidthCharacter + ']*)', 'g')
  8. module.exports = {
  9. zeroWidthCharacters,
  10. ansiEscapeCodes: new RegExp (ansiEscapeCode, 'g'),
  11. strlen: s => Array.from (s.replace (zeroWidthCharacters, '')).length, // Array.from solves the emoji problem as described here: http://blog.jonnew.com/posts/poo-dot-length-equals-two
  12. isBlank: s => s.replace (zeroWidthCharacters, '')
  13. .replace (/\s/g, '')
  14. .length === 0,
  15. blank: s => Array.from (s.replace (zeroWidthCharactersExceptNewline, '')) // Array.from solves the emoji problem as described here: http://blog.jonnew.com/posts/poo-dot-length-equals-two
  16. .map (x => ((x === '\t') || (x === '\n')) ? x : ' ')
  17. .join (''),
  18. partition (s) {
  19. for (var m, spans = []; (partition.lastIndex !== s.length) && (m = partition.exec (s));) { spans.push ([m[1] || '', m[2]]) }
  20. partition.lastIndex = 0 // reset
  21. return spans
  22. },
  23. first (s, n) {
  24. let result = '', length = 0
  25. for (const [nonPrintable, printable] of module.exports.partition (s)) {
  26. const text = Array.from (printable).slice (0, n - length) // Array.from solves the emoji problem as described here: http://blog.jonnew.com/posts/poo-dot-length-equals-two
  27. result += nonPrintable + text.join ('')
  28. length += text.length
  29. }
  30. return result
  31. }
  32. }