Shortening a string, but keeping it unique: Google Apps Script Caching Keys

In Google Caching and faking jsonP, i showed how to use google cache to avoid multiple calls to the same json data. One of things i discovered was that the key value in google cache services has an undocumented maximum length, so the challenge is to figure out how to come up with a unique key that will not break any limits, given a URL of unpredictable length.

One way to shorten the key is to use the a cryptographic hash function. Google apps script has a variety of these built-in. I selected the SHA_1 function since it is pretty collision resistant (meaning it is unlikely that 2 keys will be hashed to the same result).

So here is a function to shorten a key to a manageable size.

Testing.

Here’s a quick test, using the Google caching service. Here we’ll generate some strings of random length  and contents, shorten their key, and write them off to cache. You can use this technique to shorten any strings yet keep their uniqueness, although this post is focusing on its use for Google Caching.

The shortKeyHash() function plus a few others used in the test are available in the mcpher public library.

About brucemcp 223 Articles
I am a Google Developer Expert and decided to investigate Google Apps Script in my spare time. The more I investigated the more content I created so this site is extremely rich. Now, in 2019, a lot of things have disappeared or don’t work anymore due to Google having retired some stuff. I am however leaving things as is and where I came across some deprecated stuff, I have indicated it. I decided to write a book about it and to also create videos to teach developers who want to learn Google Apps Script. If you find the material contained in this site useful, you can support me by buying my books and or videos.

1 Comment

Leave a Reply

Your email address will not be published.


*


10 − 7 =