3 ms·
If you use React with react-router[0] (or a comparable JS-based solution), you can just apply lz-string[1] to a stringified JS object and make the resulting str
by vanderZwan 10y ago
If you use React with react-router[0] (or a comparable JS-based solution), you can just apply lz-string[1] to a stringified JS object and make the resulting string match a path. Then you need is some code to reverse the operation (lz-string -> JSON -> JS object). That's what I'm doing to create shareable state in an app I'm building for a research group.
Done naively, it will have the same problems others mentioned here: it barely shortens the URL. However, in the case of my specific app - a browser for data sets for single cell RNA sequencing - the state is largely dependent on the data set being viewed, and the data set is unchanging. What that means is that we can "externalise" the data being referred to, to pre-transform my JS object (which is an object tree) to nested arrays with integers (so a kind of "array tree") that use the data set as a look-up to reverse the operation. The latter is already a lot shorter when stringified, but also more compressible: the character set is limited to ten digits, commas and square brackets, and different values may be transformed into the same numbers, being distinguished by their position in the array tree.
To make this operation easier, I created a few helper functions to declare a "schema" that creates a recursive function for transforming the original JS object to said array of arrays, and vice-versa:
https://gist.github.com/JobLeonard/a47692a1f77bebc06c2518f321fa7efc https://gist.github.com/JobLeonard/a47692a1f77bebc06c2518f32...
As you can see in the gist, that transformation shrunk a URL of 2466 characters down to a (admittedly still crazy) 638 characters.
I was thinking on putting it on NPM but it looked so specific in its applicability that I haven't bothered turning it into a proper package yet.
[0] https://github.com/ReactTraining/react-router https://github.com/ReactTraining/react-router
[1] https://github.com/pieroxy/lz-string https://github.com/pieroxy/lz-string
- 19eightyfour 10y agoInteresting. Thanks for sharing. It sounds like a highly technical project you're optimizing there and having some success. Keep up the good work! I might take a look. edit: I looked at your gist and this is a totally great idea. I see what you're doing, converting it to make it more compressible. Very clever. If you have some ideas about how to improve my compression in this binary URI encoder, please do submit an issue or PR! Thanks for commenting!