Created
November 7, 2013 11:18
-
-
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
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
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