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