Javascript LZ String compression check if string is already compressed

1.9k Views Asked by At

I am using the LZ String library https://github.com/pieroxy/lz-string/ to compress/decompress strings and save them in localStorage.

Since the compression is going to be applied on an existing project having customers with uncompressed strings already saved on localStorage. Is there a way to know if saved string is already compressed?

Sometimes when you try to decompress an uncompressed string you get Null or an empty string but some characters still are "wrongly" decompressed. For example:

LZString.decompressFromUTF16("O"); //returns null
LZString.decompressFromUTF16("J"); //returns string 0x80

Also if I try to decompress the word Jam I don't get a Null or empty result just a string;

LZString.decompressFromUTF16("Jam"); //returns string 0x80

Here is a JsFiddle with an example https://jsfiddle.net/imurphy/8c94mhxw/

Any ideas? Thanks

1

There are 1 best solutions below

1
On

I think a better structured alternative would be to save the compressed strings in such a format that you can easily detect whether it's compressed or not. For example, rather than doing:

localStorage.property = someCompressedString;

do something like

localStorage.property = JSON.stringify({ compressed: true, payload: someCompressedString });
// or, if there isn't a chance of collisions with the following approach:
localStorage.property = 'compressed-true---' + someCompressedString;

and then check if the value is JSON-parseable or starts with compressed-true---, and extract the compressed string part as needed.