utf8-byte-length
Advanced tools
Comparing version 1.0.0 to 1.0.1
'use strict'; | ||
function isHighSurrogate(codePoint) { | ||
return codePoint >= 0xd800 && codePoint <= 0xdbff; | ||
} | ||
function isLowSurrogate(codePoint) { | ||
return codePoint >= 0xdc00 && codePoint <= 0xdfff; | ||
} | ||
// Truncate string by size in bytes | ||
@@ -11,9 +19,16 @@ module.exports = function getByteLength(string) { | ||
var byteLength = 0; | ||
var codePoint = null; | ||
var prevCodePoint = null; | ||
for (var i = 0; i < charLength; i++) { | ||
var codePoint = string.charCodeAt(i); | ||
codePoint = string.charCodeAt(i); | ||
// handle 4-byte non-BMP chars | ||
// low surrogate | ||
if (codePoint >= 0xdc00 && codePoint <= 0xdfff) { | ||
if (isLowSurrogate(codePoint)) { | ||
// when parsing previous hi-surrogate, 3 is added to byteLength | ||
byteLength += 1; | ||
if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) { | ||
byteLength += 1; | ||
} | ||
else { | ||
byteLength += 3; | ||
} | ||
} | ||
@@ -29,2 +44,3 @@ else if (codePoint <= 0x7f ) { | ||
} | ||
prevCodePoint = codePoint; | ||
} | ||
@@ -31,0 +47,0 @@ |
{ | ||
"name": "utf8-byte-length", | ||
"version": "1.0.0", | ||
"version": "1.0.1", | ||
"description": "Get byte length of utf8 string", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
12
test.js
@@ -27,2 +27,6 @@ "use strict"; | ||
// 8-byte, 4-character string | ||
var THUMB = "👍🏽"; | ||
// Tests run against both implementations | ||
@@ -38,2 +42,10 @@ [getLength, browserGetLength].forEach(function(getLength) { | ||
[repeat("a", 252) + '\uD800\uDC00', 256], | ||
[THUMB, 8], | ||
[THUMB[0], 3], | ||
[THUMB[1], 3], | ||
[THUMB[2], 3], | ||
[THUMB[3], 3], | ||
[THUMB.slice(0, 2), 4], | ||
[THUMB.slice(2, 4), 4], | ||
[THUMB.slice(1, 3), 6], | ||
].forEach(function(desc) { | ||
@@ -40,0 +52,0 @@ var string = desc[0]; |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
184026
1071