Skip to content

Instantly share code, notes, and snippets.

@timyates
Created June 25, 2012 09:35
Show Gist options
  • Select an option

  • Save timyates/2987640 to your computer and use it in GitHub Desktop.

Select an option

Save timyates/2987640 to your computer and use it in GitHub Desktop.
Adding a tr function to Groovy Lists
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