Skip to content

Instantly share code, notes, and snippets.

@rbramley
Created June 24, 2011 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbramley/1045070 to your computer and use it in GitHub Desktop.
Save rbramley/1045070 to your computer and use it in GitHub Desktop.
Groovy meta-programming to 'bump' a counter in a map
/**
* Copying and distribution of this file, with or without modification,
* are permitted in any medium without royalty provided the copyright
* notice and this notice are preserved. This file is offered as-is,
* without any warranty.
*
* @author Robin Bramley (c) 2011
*
* Groovy meta-programming to 'bump' a counter in a map for conciseness.
*/
Map.metaClass.bump = { key ->
if(delegate.containsKey(key)) {
delegate.put(key, 1 + delegate.get(key))
} else {
delegate.put(key,1)
}
}
m1 = [:]
m1.bump('foo')
assert m1['foo'] == 1
m1.bump('foo')
assert m1['foo'] == 2
m2 = [:]
m2 << m1
m2.bump('bar')
assert m2['foo'] == 2
assert m2['bar'] == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment