browser.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 getByteLength(string) {
  10. if (typeof string !== "string") {
  11. throw new Error("Input must be string");
  12. }
  13. var charLength = string.length;
  14. var byteLength = 0;
  15. var codePoint = null;
  16. var prevCodePoint = null;
  17. for (var i = 0; i < charLength; i++) {
  18. codePoint = string.charCodeAt(i);
  19. // handle 4-byte non-BMP chars
  20. // low surrogate
  21. if (isLowSurrogate(codePoint)) {
  22. // when parsing previous hi-surrogate, 3 is added to byteLength
  23. if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) {
  24. byteLength += 1;
  25. }
  26. else {
  27. byteLength += 3;
  28. }
  29. }
  30. else if (codePoint <= 0x7f ) {
  31. byteLength += 1;
  32. }
  33. else if (codePoint >= 0x80 && codePoint <= 0x7ff) {
  34. byteLength += 2;
  35. }
  36. else if (codePoint >= 0x800 && codePoint <= 0xffff) {
  37. byteLength += 3;
  38. }
  39. prevCodePoint = codePoint;
  40. }
  41. return byteLength;
  42. };