String compression in JavaScript

前端 未结 7 985
予麋鹿
予麋鹿 2020-11-29 00:31

I\'m looking for a JavaScript function that given a string returns a compressed (shorter) string.

I\'m developing a Chrome web application that saves long strings (H

7条回答
  •  情歌与酒
    2020-11-29 01:13

    I think you should also look into lz-string it's fast a compresses quite well and has some advantages they list on their page:

    What about other libraries?

    • some LZW implementations which gives you back arrays of numbers (terribly inefficient to store as tokens take 64bits) and don't support any character above 255.
    • some other LZW implementations which gives you back a string (less terribly inefficient to store but still, all tokens take 16 bits) and don't support any character above 255.
    • an LZMA implementation that is asynchronous and very slow - but hey, it's LZMA, not the implementation that is slow.
    • a GZip implementation not really meant for browsers but meant for node.js, which weighted 70kb (with deflate.js and crc32.js on which it depends).

    The reasons why the author created lz-string:

    • Working on mobile I needed something fast.
    • Working with Strings gathered from outside my website, I needed something that can take any kind of string as an input, including any UTF characters above 255.
    • The library not taking 70kb was a definitive plus. Something that produces strings as compact as possible to store in localStorage. So none of the libraries I could find online worked well for my needs.

    There are implementations of this lib in other languages, I am currently looking into the python implementation, but the decompression seems to have issues at the moment, but if you stick to JS only it looks really good to me.

提交回复
热议问题