Created
June 24, 2011 15:52
-
-
Save rbramley/1045070 to your computer and use it in GitHub Desktop.
Groovy meta-programming to 'bump' a counter in a map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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