Es una operación que se puede hacer de muchas formas, pero en groovy se puede jugar un poco con el lenguaje para que sea más chulo el código y sobretodo para poder usar lo mismo en ambas direcciones.
Ale, ahi va...
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}" |
No hay comentarios:
Publicar un comentario