Library of the Week: lz-string

You know the feeling. You need a simple generic utility library, and you're convinced you aren't the first one. You know the best code is the code you don't have to write yourself, so you consult Google, Stack Overflow and even GitHub. No dice? At least you can enjoy the challenge of writing it yourself and bask in the gratitude of others when you share it with the community.

That's how I imagine the birth of lz-string. It is designed to solve one simple yet common problem: browser local storage is limited to a mere 5Mb of data. That's not much, especially since JavaScript uses two-byte characters. lz-string provides a straightforward solution: compress your data so that more will fit into the limited space provided. Its narrow focus along with an emphasis on mobile means that it is smaller and faster than alternatives.

The improved LZW compression algorithm used by lz-string is adapted to work efficiently with 16-bit characters (more implementation details on the project page).

In order to achieve both maximum efficiency and broad browser support, lz-string supports several output encodings. For WebKit-based browsers you can call compress to produce UTF-16 strings that use all available code points. For browsers that can't store invalid UTF-16 characters in local storage, you can use compressToUTF16 instead. Depending on browser capabilities you can also use compressToBase64 (with a significantly worse compression ratio), compressToUint8Array (for browsers that support typed arrays) or the URI-safe method compressToEncodedURIComponent.

An example of compressed data might look like this:

Roman Krejčík

Roman Krejčík