string-byte-slice
Version:
Like `string.slice()` but bytewise
46 lines (37 loc) • 1 kB
JavaScript
import{
FIRST_HIGH_SURROGATE,
FIRST_LOW_SURROGATE,
LAST_HIGH_SURROGATE,
LAST_LOW_SURROGATE}from
"../codepoints.js";
import{findCharIndex}from"./indices.js";
export const byteToChar=(input,byteIndex,isStart)=>
byteIndex<0||Object.is(byteIndex,-0)?
byteToCharBackward(input,byteIndex,isStart):
byteToCharForward(input,byteIndex,isStart);
const byteToCharForward=(input,byteIndex,isEnd)=>
findCharIndex({
input,
targetByteCount:byteIndex,
firstStartSurrogate:FIRST_HIGH_SURROGATE,
lastStartSurrogate:LAST_HIGH_SURROGATE,
firstEndSurrogate:FIRST_LOW_SURROGATE,
lastEndSurrogate:LAST_LOW_SURROGATE,
increment:1,
canBacktrack:isEnd,
shift:0,
charIndexInit:0
});
const byteToCharBackward=(input,byteIndex,isEnd)=>
findCharIndex({
input,
targetByteCount:-byteIndex,
firstStartSurrogate:FIRST_LOW_SURROGATE,
lastStartSurrogate:LAST_LOW_SURROGATE,
firstEndSurrogate:FIRST_HIGH_SURROGATE,
lastEndSurrogate:LAST_HIGH_SURROGATE,
increment:-1,
canBacktrack:!isEnd,
shift:1,
charIndexInit:input.length-1
});