1
var validUtf8 = function (data) {2
const len = data.length;3
const byteBits = data.map((a) => padLeft(a.toString(2))); //convert to bit strings8
//count 1s in the front.9
while (byteBits[i].charAt(bytes) === "1") bytes++;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;14
//UTF8 chars can't be more than 4 bytes.15
if (bytes > 4) return false;17
//if we're processing more than 1 byte19
//decrement for every byte that starts with "10"20
while (i < len - 1 && byteBits[++i].startsWith("10")) bytes--;22
//check to see if we have too many or too little of the expected bytes left23
if (bytes !== 1) return false;29
const padLeft = (str, size = 8, pad = "0") =>32
: pad.repeat(size).substring(str.length % size) + str;