Repository URL to install this package:
|
Version:
0.0.15 ▾
|
/**
* @file @see https://github.com/parshap/truncate-utf8-bytes
*/
function isHighSurrogate(codePoint) {
return codePoint >= 0xd800 && codePoint <= 0xdbff;
}
function isLowSurrogate(codePoint) {
return codePoint >= 0xdc00 && codePoint <= 0xdfff;
}
// Truncate string by size in bytes
function truncate(getLength, character, byteLength) {
if (typeof character !== 'string') {
throw new Error('Input must be string');
}
const charLength = character.length;
let curByteLength = 0;
let codePoint;
let segment;
for (let i = 0; i < charLength; i += 1) {
codePoint = character.charCodeAt(i);
segment = character[i];
if (isHighSurrogate(codePoint) && isLowSurrogate(character.charCodeAt(i + 1))) {
i += 1;
segment += character[i];
}
curByteLength += getLength(segment);
if (curByteLength === byteLength) {
return character.slice(0, i + 1);
}
else if (curByteLength > byteLength) {
return character.slice(0, i - segment.length + 1);
}
}
return character;
}
const getLength = Buffer.byteLength.bind(Buffer);
const fromStringToTruncatedUtf8 = truncate.bind(null, getLength);
export { fromStringToTruncatedUtf8 };
export default fromStringToTruncatedUtf8;
//# sourceMappingURL=fromStringToTruncatedUtf8.js.map