Creating a crypto digest of some content is a neat trick used by github (and torrent sharing sites) to know if the content of two files is identical. There are plenty of other uses for this idea, and in Apps Script, one of the most useful I find is to generate a short, but unique, key for items I'm writing to cache. Quite often, the data being written to cache is based on a set of parameters that is larger than the current limit for the Cache Service key size (250 characters)
A simple way to create a short key size is to create a sha1 digest of the data that uniquely identifies the data being saved.
Here's some examples, using my keyDigest function from my cUseful library.
The keyDigest function can take any number or type of arguments and create a digest out of them.
Let's say you want a quick a way to test whether a bunch of values are the same as each other. One use might be to see if an entire spreadsheet contains the same data as another. This will show true if the two ranges contain the same data.
Here's some more examples
This will return true
But if you reverse the order of declaration, it will return false even though they are ostensibly the same values. This is because the order of stringification by JSON.stringify is not controllable, so be careful when passing objects as key values. Of course only stringifyable objects can be used (as opposed to built in Apps Script objects).
The sha1 digest in theory could produce a collision - meaning that two different sets of data could return the same key. The chances of that happening though are at least 251 against (according to this paper). That's 2,251,799,813,685,248 to 1. By comparison the chances of winning the UK lottery are 14,000,000 to 1 and being struck by lightning in your lifetime are 12,000 to 1.
Here's the key for the cUseful library, and it's also on github, or below.
For more like this, see Google Apps Scripts snippets. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.
You want to learn Google Apps Script?
Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly.
Services > Desktop Liberation - the definitive resource for Google Apps Script and Microsoft Office automation > Google Apps Scripts snippets >