1
var validUtf8 = function (data) {
2
const len = data.length;
3
const byteBits = data.map((a) => padLeft(a.toString(2))); //convert to bit strings
4
let bytes,
5
i = 0;
6
while (i < len) {
7
bytes = 0;
8
//count 1s in the front.
9
while (byteBits[i].charAt(bytes) === "1") bytes++;
10

11
//if we have only 1 byte to process expect more than 1 byte, it should fail.
12
if (len === 1 && bytes > 0) return false;
13

14
//UTF8 chars can't be more than 4 bytes.
15
if (bytes > 4) return false;
16

17
//if we're processing more than 1 byte
18
if (bytes > 1) {
19
//decrement for every byte that starts with "10"
20
while (i < len - 1 && byteBits[++i].startsWith("10")) bytes--;
21

22
//check to see if we have too many or too little of the expected bytes left
23
if (bytes !== 1) return false;
24
} else i++;
25
}
26
return true;
27
};
28

29
const padLeft = (str, size = 8, pad = "0") =>
30
str.length >= size
31
? str
32
: pad.repeat(size).substring(str.length % size) + str;

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0