Exercise - Arrays Reverse

by Ryan Morris

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
 */

console.log(reverseArray(["A", "B", "C", "D"]));
// → ["C", "B", "A"];

function reverseArray(arr) {
    
    var newArray = [];
    
    var j=0;
    
    for (var i=arr.length-1; i>=0; i--) {
        
        newArray[j] = arr[i];
        j++;
        
    }
    
    return newArray;
    
}

//console.log(reverseArray(arr));


/* 
 * 2)
 * Upgrade the reverseArray function so that when you pass a value 
 * that is not an array it will throw an exception
 */

function reverseArray(arr) {
    
    if (!Array.isArray(arr)) {
        throw new Error("Not an array");
    }
    
    var newArray = [];
    
    var j=0;
    
    for (var i=arr.length-1; i>=0; i--) {
        
        newArray[j] = arr[i];
        j++;
        
    }
    
    return newArray;
    
}

reverseArray("string");

/*
 * 3) Bonus
 * Create a new function, reverseArrayInPlace(arr)
 * which does the same but does NOT use two arrays during the reversal process. 
*/

function reverseArray(arr) {
    
    if (!Array.isArray(arr)) {
        throw new Error("Not an array");
    }
    
    var newArray = [];
    
    var j=0;
    
    for (var i=arr.length-1; i>=0; i--) {
        
        newArray[j] = arr[i];
        j++;
        
    }
    
    return newArray;
    
}