Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created May 1, 2019 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/1823113482f190d7946e3e1ba36966f5 to your computer and use it in GitHub Desktop.
Save parzibyte/1823113482f190d7946e3e1ba36966f5 to your computer and use it in GitHub Desktop.
const invertirManual = arreglo => {
// Guardar de una vez la longitud para hacer más legible el código
let longitudDelArreglo = arreglo.length;
// Recorrer arreglo hasta la mitad. Si es impar, se va al entero anterior más
// próximo. P. ej. 5 / 2 => 2
for (let x = 0; x < longitudDelArreglo / 2; x++) {
// Respaldar el valor actual
let temporal = arreglo[x];
// Calcular el índice contrario, es decir, el del otro lado de la mitad; el cual irá descendiendo
let indiceContrario = longitudDelArreglo - x - 1;
// En el actual ahora está el del otro lado
arreglo[x] = arreglo[indiceContrario];
// Y en el otro lado, el que estaba originalmente en el actual
arreglo[indiceContrario] = temporal;
}
// No regresamos nada porque ya modificamos al arreglo internamente
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment