truncate.js 977 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. };