Created
June 25, 2012 09:35
-
-
Save timyates/2987640 to your computer and use it in GitHub Desktop.
Adding a tr function to Groovy Lists
This file contains hidden or 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
| def tr = { inputs, outputs -> | |
| (inputs,outputs) = [inputs,outputs].collect { it instanceof List ? it : [ it ] } | |
| assert inputs.size() == outputs.size(), 'tr: Inputs and outputs must be the same size' | |
| delegate.collect { item -> | |
| inputs.indexOf( item ).with { idx -> | |
| idx == -1 ? item : outputs[ idx ] | |
| } | |
| } | |
| } | |
| List.metaClass.tr = tr | |
| def names = ['A','B','C','A','D'] | |
| assert ['X','B','C','X','D'] == names.tr( 'A', 'X' ) | |
| assert ['X','B','Y','X','D'] == names.tr( ['A','C'], ['X','Y'] ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment