Skip to content

Instantly share code, notes, and snippets.

@anhkind
Forked from revolunet/lzw_encoder.js
Created August 29, 2025 02:13
Show Gist options
  • Save anhkind/c95654dd7d9e47ac2a8165e74f6912f6 to your computer and use it in GitHub Desktop.
Save anhkind/c95654dd7d9e47ac2a8165e74f6912f6 to your computer and use it in GitHub Desktop.

Revisions

  1. @revolunet revolunet created this gist Feb 25, 2011.
    52 changes: 52 additions & 0 deletions lzw_encoder.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    // LZW-compress a string
    function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
    currChar=data[i];
    if (dict[phrase + currChar] != null) {
    phrase += currChar;
    }
    else {
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    dict[phrase + currChar] = code;
    code++;
    phrase=currChar;
    }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
    out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
    }

    // Decompress an LZW-encoded string
    function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
    var currCode = data[i].charCodeAt(0);
    if (currCode < 256) {
    phrase = data[i];
    }
    else {
    phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
    }
    out.push(phrase);
    currChar = phrase.charAt(0);
    dict[code] = oldPhrase + currChar;
    code++;
    oldPhrase = phrase;
    }
    return out.join("");
    }