Exercise - Arrays Reverse
JavaScript
/**
* Reversing an array
(without Array.reverse())
*
* 1)
* Create a function, reverseArray(arr), that expects a single array as an argument
* It will return a new array, with all the values in reverse order
*/
reverseArray = function(arr) {
if (Array.isArray(arr)) {
var len = arr.length;
for (var i=0; i<=len/2; i++) {
var temp = arr[i];
arr[i] = arr[len-i-1];
arr[len-i-1] = temp;
}
return arr;
} else {
return NaN;
}
}
console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];
console.log(reverseArray({}));
/*
* 2)
* Upgrade the reverseArray function so that when you pass a value
* that is not an array it will throw an exception
*/
/*
* 3) Bonus
* Create a new function, reverseArrayInPlace(arr)
* which does the same but does NOT use two arrays during the reversal process.
*/