Skip to content

Instantly share code, notes, and snippets.

@ivanarrizabalaga
Created November 7, 2013 11:18
Show Gist options
  • Save ivanarrizabalaga/7353040 to your computer and use it in GitHub Desktop.
Save ivanarrizabalaga/7353040 to your computer and use it in GitHub Desktop.
Easy way to move a selection of items within a list up and down in Groovy
import java.util.Collections
//Input
def elements=['a','b','c','d','e']
def selectedIndices=[1,2,3]
boolean isMovingUp=false
println "Initial: ${elements}"
println "Selection: ${selectedIndices.collect{elements[it]}}"
println "Direction: ${isMovingUp?'<':'>'}"
//Offset + Iteration according to direction
int offset=isMovingUp?-1:1
def iterate=isMovingUp?"each":"reverseEach"
selectedIndices."$iterate"{ selectedIndex ->
use(Collections){
elements.swap(selectedIndex, selectedIndex + offset)
}
}
//Output
println "Final: ${elements}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment