From afe66779cd24b93a83359adbac1589ec818f4e1a Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Fri, 6 Jan 2023 00:52:59 -0800 Subject: [PATCH] Simplify parsing logic I thought there would be more switch cases but it's only 2 --- script.js | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/script.js b/script.js index 49e05a3..5662c1a 100644 --- a/script.js +++ b/script.js @@ -39,31 +39,32 @@ function calculateOutput(input) { } function parseBytes(bytes) { - switch (bytes.length) { - // UTF-8 byte length of 1 is always encoded with this pattern: 0xxxxxxx - case 1: - return `0${bytes[0].substring(2)}`; + // A UTF-8 encoded code point with a byte length of 1 is always encoded with this pattern: 0xxxxxxx + if (bytes.length === 1) { + return `0${bytes[0].substring(2)}`; + } - // All other lengths follow the same pattern - // Examples: - // - For 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx - // - For 4 bytes: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - default: - let template = ''; + // All other UTF-8 byte lengths follow the same pattern + // Examples: + // Length = 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx + // Length = 4 bytes: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // Length = 5 bytes: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + else { + let template = ''; - // The number of insignificant bits in the first byte are always the length of the array plus one 0 - const initialLength = bytes.length; - const firstByte = bytes.shift(); - template += `${firstByte.substring(0, initialLength + 1)}`; - template += `${firstByte.substring(initialLength + 1)}`; + // The number of insignificant bits in the first byte is always the length of the array plus one + const initialLength = bytes.length; + const firstByte = bytes.shift(); + template += `${firstByte.substring(0, initialLength + 1)}`; + template += `${firstByte.substring(initialLength + 1)}`; - // Remaining bytes always have 2 insignificant bits - for (const byte of bytes) { - template += `10`; - template += `${byte.substring(2)}`; - } + // Remaining bytes always have 2 insignificant bits + for (const byte of bytes) { + template += `10`; + template += `${byte.substring(2)}`; + } - return template; + return template; } } -- 2.47.3