truncate.js 977 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. function isHighSurrogate(codePoint) {
  3. return codePoint >= 0xd800 && codePoint <= 0xdbff;
  4. }
  5. function isLowSurrogate(codePoint) {
  6. return codePoint >= 0xdc00 && codePoint <= 0xdfff;
  7. }
  8. // Truncate string by size in bytes
  9. module.exports = function truncate(getLength, string, byteLength) {
  10. if (typeof string !== "string") {
  11. throw new Error("Input must be string");
  12. }
  13. var charLength = string.length;
  14. var curByteLength = 0;
  15. var codePoint;
  16. var segment;
  17. for (var i = 0; i < charLength; i += 1) {
  18. codePoint = string.charCodeAt(i);
  19. segment = string[i];
  20. if (isHighSurrogate(codePoint) && isLowSurrogate(string.charCodeAt(i + 1))) {
  21. i += 1;
  22. segment += string[i];
  23. }
  24. curByteLength += getLength(segment);
  25. if (curByteLength === byteLength) {
  26. return string.slice(0, i + 1);
  27. }
  28. else if (curByteLength > byteLength) {
  29. return string.slice(0, i - segment.length + 1);
  30. }
  31. }
  32. return string;
  33. };