]> git.ardis.lu - utf-8-visualizer/commitdiff
Simplify parsing logic
authorArdis Lu <ardisglu@gmail.com>
Fri, 6 Jan 2023 08:52:59 +0000 (00:52 -0800)
committerArdis Lu <ardisglu@gmail.com>
Fri, 6 Jan 2023 08:52:59 +0000 (00:52 -0800)
I thought there would be more switch cases but it's only 2

script.js

index 49e05a32ceb2f1e446af11846650d61f379489cb..5662c1a162b472b06c9068d5c0b1c8913e568988 100644 (file)
--- 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 `<span class="insignificant">0</span><span class="significant">${bytes[0].substring(2)}</span>`;
-
-    // All other lengths follow the same pattern
-    // Examples: 
-    // - For 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx
-    // - For 4 bytes: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
-    default:
-      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 += `<span class="insignificant">${firstByte.substring(0, initialLength + 1)}</span>`;
-      template += `<span class="significant">${firstByte.substring(initialLength + 1)}</span>`;
-
-      // Remaining bytes always have 2 insignificant bits
-      for (const byte of bytes) {
-        template += `<span class="insignificant">10</span>`;
-        template += `<span class="significant">${byte.substring(2)}</span>`;
-      }
-
-      return template;
+  // A UTF-8 encoded code point with a byte length of 1 is always encoded with this pattern: 0xxxxxxx
+  if (bytes.length === 1) {
+    return `<span class="insignificant">0</span><span class="significant">${bytes[0].substring(2)}</span>`;
+  }
+
+  // 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 is always the length of the array plus one
+    const initialLength = bytes.length;
+    const firstByte = bytes.shift();
+    template += `<span class="insignificant">${firstByte.substring(0, initialLength + 1)}</span>`;
+    template += `<span class="significant">${firstByte.substring(initialLength + 1)}</span>`;
+
+    // Remaining bytes always have 2 insignificant bits
+    for (const byte of bytes) {
+      template += `<span class="insignificant">10</span>`;
+      template += `<span class="significant">${byte.substring(2)}</span>`;
+    }
+
+    return template;
   }
 }
 
This page took 0.032809 seconds and 4 git commands to generate.