CNC4ME Blog

String Compression and URL Encoding

Cover Image for String Compression and URL Encoding
Kevin Hill
Kevin Hill

String Compression and URL Encoding

While learning TypeScript, I frequently use the amazing playground webapp they made available to developers. It has proven invaluable to developers to be able to send examples or issues directly to collegues via a single URL. You can save links to content you create with no strings attached. You don't have to register or log-in, no downloads, it's free to share! I really like this concept, so I decided that I was going to see if I could implement it for my playground.

Step 1 - Figure out how they do it

Here is the link we will be examining.

Ignoring the domain, we start from /play which is the route they have given to this app, don't need that, moving on. #code/ is next which is the hash key they are using to store the editor content. After the final / is

PQKhFgCgAIWgVAFgSwM7TdAxgewLYAOATgKaqokAm0AhgHbUl26VUZ0AuO0HiJ0AVQBKAGR7cARvxoSANvy7Qp0VIhqlKAOiixgQA

which is some sort of hashing or encoding of our input, since it is definitely not the source.

Step 2 - Investigating

I need to see the source, I need to know, and I am happy to be an open source developer and part of a movement towards open source. This means the the TypeScript playgrounds' source is available for me to take a look. I find that the syntax for links is well documented, so we are on the right track. I am not sure where this file and method might be, so lets use Github's search. Since they are using #code/ in the URL, we will search for "hash" in the repository for usage of location.hash. Our search ends here with the code for how they are decoding that wacky URL. Some library called lzstring

Step 3 - Research

Since this is a webapp, our first logical search will be on NPM and it brings up the package lz-string by pieroxy. So here we have it, they are taking the contents of the editor, running through this compression library, and appending it to the URL. I thought this might be complicated, but it seems pretty straight forward. Next step, just need to make a similiar implementation for my site, using this library.

Step 4 - Implementation

Since I am using this fantastic wrapper library around the Monaco editor, it seemed like using the onChange andn onMount methods would make sense for our logic.