Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Eazybright/e9386f28af28d6ca69118d1c9e44bb18 to your computer and use it in GitHub Desktop.
Save Eazybright/e9386f28af28d6ca69118d1c9e44bb18 to your computer and use it in GitHub Desktop.
Running solutions for Eloquent Javascript - comments are welcome!
/****************************
Chapter 4: Reversing an Array
*****************************
Arrays have a method reverse, which changes the array by inverting the order in which its elements appear.
For this exercise, write two functions, reverseArray and reverseArrayInPlace.
The first, reverseArray, takes an array as argument and produces a new array that has the same elements in the inverse order.
The second, reverseArrayInPlace, does what the reverse method does:
it modifies the array given as argument in order to reverse its elements. Neither may use the standard reverse method.
*/
function reverseArray(input){
var output = [];
for (i = 0; i < input.length; i++){
output.unshift(input[i]);
}
return output;
}
function reverseArrayInPlace(input){
for (i = 1; i < input.length; i++){
var remove = input.splice(i,1)
input.unshift(remove[0]);
}
return input;
}
console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];
console.log(reverseArrayInPlace([1, 2, 3, 4, 5]));
// → [5, 4, 3, 2, 1]
console.log(reverseArrayInPlace([1, 2, 3, 4, 5, 6]));
// → [6, 5, 4, 3, 2, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment