Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Last active September 18, 2018 23:42
Show Gist options
  • Save ultim8k/19923d6646c9497d626407de46213a75 to your computer and use it in GitHub Desktop.
Save ultim8k/19923d6646c9497d626407de46213a75 to your computer and use it in GitHub Desktop.
Reverse an array fast by "folding" it and counting until the middle.
// This son of a bitch goes until the middle of the array
// and flips each item with it's mirrored item from the end
let arr = [1, 7, 2, 5, 9];
const halfLength = arr.length / 2;
const maxI = arr.length - 1;
for (let i = 0; i <= parseInt(halfLength); i=i+1) {
let m = maxI - i;
let a = arr[i];
let b = arr[m];
console.log(i, m, a, b);
arr[i] = b;
arr[m] = a;
}
console.log(arr);
// And a more functional way so that I can sleep better in the night
const revertArray = (array = [], index = 0) => {
if (index >= parseInt(array.length / 2)) {
return array;
}
const reverseIndex = array.length - 1 - index;
let pin = [...array];
pin[index] = array[reverseIndex];
pin[reverseIndex] = array[index];
return revertArray(pin, index + 1);
}
const mirrored = revertArray(nums);
console.log(mirrored);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment