Files
novafarma/old_logic/src_backup_1768938138/utils/Compression.js
2026-01-21 01:08:21 +01:00

45 lines
1.6 KiB
JavaScript

// Utility class for string compression (LZW algorithm)
// Used to reduce save file size in localStorage
class Compression {
static compress(s) {
if (s == null) return "";
var dict = {}, data = (s + "").split(""), out = [], currChar, phrase = data[0], 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("");
}
static decompress(s) {
if (s == null) return "";
if (s == "") return null;
var dict = {}, data = (s + "").split(""), currChar = data[0], oldPhrase = currChar, out = [currChar], code = 256, 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 + oldPhrase.charAt(0));
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
}