JSFiddle - React, Tailwind, and code Playground

by brigand

HTML

<!DOCTYPE html>

<head>
  <meta charset="utf-8" />
</head>

<body>
  <div>
    <textarea id="input" rows="4" cols="50"></textarea>
    <button id="action" type="submit">Submit</button>
  </div>
  <div style="margin: 15px 0 0 0">
    <div id="encoded"></div>
  </div>
  <div style="margin: 15px 0 0 0">
    <div id="output"></div>
  </div>
  <script src="test.js"></script>
</body>

</html>

JavaScript

const input = document.querySelector("#input");
const encoded = document.querySelector("#encoded");
const output = document.querySelector("#output");
const action = document.querySelector("#action");

const LZW = (function() {
  return {
    encode: function(string) {
      if (!string)
        return string;
      var dict = new Map();
      var data = (string + "").split("");
      var out = [];
      var phrase = data[0];
      var code = 256;

      for (let i = 1; i < data.length; i++) {
        let currentCharacter = data[i];
        if (dict.has(phrase + currentCharacter)) {
          phrase += currentCharacter;
        } else {
          out.push(phrase.length > 1 ? dict.get(phrase) : phrase.charCodeAt(0));
          dict.set(phrase + currentCharacter, code);
          code++;
          phrase = currentCharacter;
        }
      }

      out.push(phrase.length > 1 ? dict.get(phrase) : phrase.charCodeAt(0));
      for (let i = 0; i < out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
      }
      return out.join("");
    },
    decode: function(string) {
      if (!string)
        return string;
      var dict = new Map();
      var data = (string + "").split("");
      var currentCharacter = data[0];
      var code = 256;
      var oldPhrase = currentCharacter;
      var out = [currentCharacter];
      var phrase;

      for (let i = 1; i < data.length; i++) {
        let currentCode = data[i].charCodeAt(0);
        if (currentCode < 256) {
          phrase = data[i];
        } else {
          phrase = dict.has(currentCode) ? dict.get(currentCode) : (oldPhrase + currentCharacter);
        }
        out.push(phrase);
        currentCharacter = phrase.charAt(0);
        dict.set(code, oldPhrase + currentCharacter);
        code++;
        oldPhrase = phrase;
      }

      return out.join("");
    }
  };
})();

//I google searched for the word, "test", then copied the URL at the top of the browser.
input.value =...