Skip to content

Instantly share code, notes, and snippets.

@davidpelfree
Created August 23, 2012 13:36
Show Gist options
  • Save davidpelfree/3436661 to your computer and use it in GitHub Desktop.
Save davidpelfree/3436661 to your computer and use it in GitHub Desktop.
For analytics, here's an easy and elegant way to devide numeric value (document size in this case) to groups of ranges using Groovy.
long contentLength = doc.getContentLength() // never mind where the long value comes from.
// Classify doc size. Notice that numbers in map's key have to be ordered (TreeMap) and last key should be Integer.MAX_VALUE:
// This is map of max length size value to a string describing this group
def docGroupMap = new TreeMap([2048:'0-2 KB', 5120:'2-5 KB', 10240:'5-10 KB', (Integer.MAX_VALUE): '10+ KB'])
// The find() method iterates the map and checks every key with the expression in its closure-parameter.
// Since TreeMap is used, the keys are ordered.
// Once the expression is true, the value is being assigned to the string.
// The value is a string describing textually the document size group.
String docSizeGroup = docGroupMap.find{k,v ->
contentLength < k
}.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment