Chapter 4 - Exercises

You can check for the solutions of the problems by using the following link.
https://eloquentjavascript.net/2nd_edition/code/

Just select the chapter and the according exercise. You can even get a running solution by clicking the button “show the solution”. But at first, you should try to develop a running version on your own. This is very important to get better. By doing this you can compare the solution provided with your own one and also analyse the shortcomings of your solution. You can even run your code by pasting it and clicking on the “run code” button.

Now to the problem of the two different functions to reverse an array. To be honest I didn’t understand the difference of these exercises, too. I implemented only the first version and then I had a look at the two solutions. By looking at the solutions I figured out what the difference was:

First exercise by example without a loop for better understanding:

var oldArray = ["one", "two", "three", "four"];
var newArray = ["undefined", "undefined", "undefined", "undefined"];
newArray[0] = oldArray[3];
newArray[1] = oldArray[2];
newArray[2] = oldArray[1];
newArray[3] = oldArray[0];

console.log(newArray); will get you ["four", "three", "two", "one"].

The idea of the solution is that you create a new array. One array is iterated from start to end, while the other array is iterated from end to start to get the order of the elements reversed. Sure you can also start with an empty second array! So the code above is not considered as good programming style, it is just to show you how the algorithm for reversing the array works. If you do the exercises you will need loops for sure!

Second exercise by example without a loop for better understanding:
In the second exercise you don’t have a second array! Just use the first one!

var oldArray = ["one", "two", "three", "four"];
//You will need an additional variable for saving one value! Sometimes it is called "Dummy" variable.
var saveThisForAMoment = "undefined";

//Swapping the first element with the last element of the array.
saveThisForAMoment = oldArray[0];
oldArray[0] = oldArray[3];
oldArray[3] = saveThisForAMoment;

//Swapping the second element with the second last element of the array.
saveThisForAMoment = oldArray[1];
oldArray[1] = oldArray[2];
oldArray[2] = saveThisForAMoment;

console.log(oldArray); will get you ["four", "three", "two", "one"].

The cool thing about this solution is, that you only go half through the array. You start with swapping the values of the first array element with the last array element.

But what about array with and odd number of elements? Lets look just at the values:

“one” → “five”
“two” → “four”
“three” → “three”
“four” → “two”
“five” → “one”

The element in the middle does not change at all. “three” stays “three”. So you can stop after swapping the values “one” and “two” with “five” and “four”.

I hope this helps! Don’t be disappointed in your abilities. Getting a good programmer really takes some time. And it also took me quite some time to figure things out. By learning the syntax of a programming language you will not become a good programmer at once! It always take some “blood, sweat and tears” like Ivan always says to get more experience and also learn about the pitfalls!

1 Like

This is my solution to the exercise:

Create a range with flexible stepping and handling negative stepping:

       function range(start, stop, step = 1){
         let rangeArray=[];
         if (start>stop&&step<0){
           for (n=start; n>=stop; n=n+step){
             rangeArray.push(n);
           }
         }
         else if (start<stop&&step>0){
           for (n=start; n<=stop; n=n+step){
             rangeArray.push(n);
           }
         }
         else{
           return null;
         }
         return rangeArray;
       }

Summing up a range:

       function rangeSum(numberArray){
         let sum = 0;
         for (let i=0; i < numberArray.length; i++){
           sum += numberArray[i];
         }
         return sum;
       }

Since I bumped in to the issue of receiving a NaN result with console.log(sum) due to missing to initialize the sum (let sum; instead of let sum = 0;)

Reversing an array, my solution utilizes the .unshift() array operation rather the using a loop to counting down.

       function reverseArray(forwardArray){
         let backwardArray = [];
         for (let n=0; n<forwardArray.length;n++){
           backwardArray.unshift(forwardArray[n]);
         }
         return backwardArray;
       }
1 Like

Implementation of range (without step)

    function range(start, end) {
      var intArray = [];
      for (var index = start; index <= end; index++) intArray.push(index);
      return intArray;
    }

    function sum(arrayToSum){
      totalSum = 0;
      for (let summand of arrayToSum) totalSum += summand;
      return totalSum;
    }

    console.log(sum(range(1,10)));

The first function is just simple, because the for loop has everything you need to implement it right away. In the function sum I just used the syntax let summand of arrayToSum to iterate through each element of the array without having to take care of indices or boundaries.

Implementation of range (with step)

    //Setting step to 1, if argument is not provided.
    function range(start, end, step=1) {
      var intArray = [];

      //Setting step to 1 instead of 0 to prevent endless for loop!
      if (step == 0) step=1;

      //Correcting the sign of step when stepping in the wrong direction.
      if ((step < 0 && start < end) || (step > 0 && start > end)) step = -step;

      //Matching the condition to exit loop according to the sign of step.
      if (step > 0) {
        for (var index = start; index <= end; index += step) intArray.push(index);
      } else {
        for (var index = start; index >= end; index += step) intArray.push(index);
      }
      return intArray;
    }

    function sum(arrayToSum){
      totalSum = 0;
      for (let summand of arrayToSum) totalSum += summand;
      return totalSum;
    }
    console.log(range(15,10,-1));
    console.log(sum(range(15,10,-1)));

In this version I tried to make the code more robust by checking if the steps go into the correct direction. If not I just turned the sign of the step in order to make things right.

Implemanation of reverseArray and reverseArrayInPlace

    myArray = ["one", "two", "three", "four", "five"];

    function reverseArray(oldArray) {

      var reversedArray = [];

      for (var index = oldArray.length - 1; index >= 0; index--) {
        reversedArray.push(oldArray[index]);
      }
      return reversedArray;
    }

    function reverseArrayInPlace(oldArray) {
      var dummy = "";
      const maxIndex = oldArray.length - 1;
      for (var index = 0; index <= oldArray.length % 2; index++) {
        dummy = oldArray[index];
        oldArray[index] = oldArray[maxIndex - index];
        oldArray[maxIndex - index] = dummy;
      }
      return oldArray;
    }
    console.log(myArray);
    console.log(reverseArray(myArray));
    console.log(myArray);
    console.log(reverseArrayInPlace(myArray));

Ideas behind the two functions

function reverseArray
This function reverses the order on the array given to it as an argument by creating a new empty array and filling it in the reverse order of the original array. This is achieved by going through the original array from the highest index to the lowest index which is 0.

function reverseArrayInPlace
This function reverses the order of the original array by swapping its values. So the first element get the value of the last one and vice versa. To prevent overwriting one value in the process this value is temporary saved in the variable dummy:
dummy = first_element;
first_element = last_element;
last_element = dummy;

After performing this swap the algorithm goes on by swapping the second element with the second last one. Since you swap the first half of the array with the second half of the array you will only have to go from index = 0 to index = oldArray.length % 2. But what about an array with an odd number of element? The element in the middle (index = oldArray.length % 2 + 1) is not changed at all, because the index of this element stays the same!

1 Like

The Sum of a Range - Exercise 1

function range(start, end, step) {
        var intArray = [];    // define empty array
        if (step == null) {   // check if step was entered, if not, set to 1
          step = 1;
        };

        if (step > 0) {       // If step is positive, add step intervals until end is reached
          for (var i = start; i <= end; i += step) {
            intArray.push(i);
          };

        } else {              // If step is negative, subtract step intervals until end is reached
          for (var i = start; i >= end; i += step)
            intArray.push(i);
          };
          return intArray;
        };

      function sum(intArray) {
        var sumTotal = 0;
        for (var i = 0; i < intArray.length; i++) {
          sumTotal += intArray[i];
        };
        return sumTotal;
      };

      console.log(range(1, 10));
      console.log(range(5, 2, -1));
      console.log(sum(range(1, 10)));

1 Like

Reversing an Array - Exercise 2

function reverseArray(array) {
        var output =[];
        for (var i = 0; i < array.length; i++) {
          output[i] = array[array.length - 1 - i];
        }
        return output;
      };

      function reverseArrayInPlace(array) {
        reverseArray(array);
        return array;
      };

      console.log(reverseArray(["Mazda", "Opel", "Mercedes"]));
      console.log(reverseArrayInPlace(["Mazda", "Opel", "Mercedes"]));
1 Like

The sum of a range:

function range( start, end, increment ) {

var result = [];

if ( increment == undefined )
increment = 1;

numLoops = Math.abs( (end - start)/ increment ) + 1 ;

for ( var i = 0; i < numLoops; i ++ ) {

result.push( start );
 
start += increment;

}

return result;
}

function sum( numArray ) {

var arrayTotal = 0;

numLoops = numArray.length;

for ( var i = 0; i < numLoops; i ++ ) {

arrayTotal += numArray[i];

}

return arrayTotal;
}

Reverse array:

function reverseArray(array) {
result = [];
for (let item of array) {
result.unshift(item);
}
return result;
}

function reverseArrayInPlace(array) {
let len = array.length;
for (let i = 0; i < Math.floor(len/2); i++) {
console.log(i, len-i-1, array[i], array[len-i-1], array);
let swap = array[i];
array[i] = array[len-i-1];
array[len-i-1] = swap;
}
return array;
}

console.log(reverseArray([“A”, “B”, “C”]));

let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

1 Like

function range(start, end, step = start < end ? 1 : -1) {
let array = [];

if (step > 0) {
for (let i = start; i <= end; i += step) array.push(i);
} else {
for (let i = start; i >= end; i += step) array.push(i);
}
return array;
}

function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}

var fruits = [“apple”, “banana”, “orange”, “pineapple”];

function reverseArray(myArray){
var newArray= [];
for (var i = myArray.length - 1; i >=0; i–){
newArray.push(myArray[i]);
}
return newArray;
}

function reverseArrayInPlace(myArray) {
for (i = 0; i < myArray.length; i ++) {
let append = myArray.pop();
myArray.splice(i, 0, append);
}
return myArray;
}

console.log(reverseArray(fruits));
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

1 Like

Finally!!! Sum(Range())

function range(start, end, interval){
for (var i=start;(i<=end&&start<=end)||(i>=end&&start>=end);i+=interval){
newArray.push(i);
}return newArray};

function sum(){var num=newArray.length;
var total=0; for (var n=0; n<num; n++){ total += newArray[n]}return total};
1 Like

Reversing an array-

function reverseArray(n){
var newArray=[];
var num = n.length;
for(var i=0; i<num;i++){newArray.push(n.pop(i))};return newArray};

Reverse array in place-

function reverseArrayInPlace(array){
var rayLength=array.length
for (i=0;i<rayLength;i++){
array.splice(i,0,array.pop())
}return array;
}

Would either of these two functions give me a side effect? I feel they both work well and they are both about the same amount of characters. But I suppose with the reverse array in place there is less room for confusion as there is only 1 variable.

1 Like

Here’s my solutions:

THE SUM OF A RANGE

// Creating an array with a loop function for the range 
// with "start" and "end".
// Adding parameter "step" to the range.
	var range = function(start, end, step){
	   var arr = [];
	     cnt = start;

// Conditions for the "step".
	if (step == null){
		step = 1;
		}

	if (step > 0) {
	 while (cnt <= end){
			arr.push(cnt);
			cnt += step;
			}
		return arr;
		};

     if (step < 0){
	  while (cnt >= end){
			arr.push(cnt);
			cnt += step;
			}
		return arr;
		};
		}

var sum = function(arr){
	var total = 0;
	while (arr.length > 0){

	// Popping off a value added to the total,
	// so in the end the array won't have any values in it

		total = total + arr.pop();
	}
	return total
};

console.log(sum(range(1,10)));
console.log(range(5,2,-1));
console.log(range(1,10,2));

REVERSING AN ARRAY

const reverseArray = (arr) => {
	let result = []
		for (let elem of arr){
			result.unshift(elem)
		}
		return result
	}
	const arr = [1,2,3,4,5]

	console.log(arr)
	console.log(reverseArray(arr))
	
const reverseArrayInPlace = (arr) => {
	let temp
		for (let i = 0; i < arr.length / 2; i++){
			temp = arr[i]
			arr[i] = arr[arr.length - 1 -i]
			arr[arr.length - 1 - i] = temp
		}
		return arr
}

const arr = [1,2,3,4,5]
console.log(arr)
console.log(reverseArrayInPlace(arr))
console.log(arr)

The function reverseArray is a pure function since it doesn’t modify the array. The fact that it’s a pure function makes it more likely not to be as useful as functions with side effects. Also it might be slower.

  1. The Sum of a Range
function range(start, end, step = start < end ? 1:-1) {
      let n = [];

      if (step>0){
        for (let x = start; x <= end; x += step) n.push(x);
      }
      else{
          for (let x = start; x >= end; x += step) n.push(x);
        }
      return n;
    }

    function sum(array){
      let total = 0;
      for (let value of array){
        total += value;
      }
      return total;
    }

    console.log(range(1,10));
    console.log(range(5,2,-1));
    console.log(sum(range(1,10)));
  1. Reversing an Array
function reverseArray(array) {
  let output = [];
  for (let y = array.length - 1; y >= 0; y--) {
    output.push(array[y]);
  }
  return output;
}

function reverseArrayInPlace(array) {
  for (let y = 0; y < Math.floor(array.length / 2); y++) {
    let old = array[y];
    array[y] = array[array.length - 1 - y];
    array[array.length - 1 - y] = old;
  }
  return array;
}

console.log(reverseArray(["Sennheiser", "Hifiman", "AKG"]));

let arrayHeadphones = ["Audeze","Beyerdinamic","ZMF","Phillips","Campfire"];
reverseArrayInPlace(arrayHeadphones);
console.log(arrayHeadphones);

1a
function rangeFunction(start,end){
let alist = [start];
for(var i = start +1; i < end +1; i++){
alist.push(i);
}
return alist;
}

1b
function summer(listName){
let answer = 0;
for(var i=0; i<listName.length; i++){
answer += listName[i];
}
return answer;
}

1c
function rangeFunction(start,end,step=1){
let alist = [start];
for(var i = start +step; i < end +1; i+=step){
alist.push(i);
}
return alist;
}

2a
function reverseArray(arrayName){
var newArray = [];
for(var i = arrayName.length-1; i>= 0; i–){
newArray.push(arrayName[i]);
}
return newArray;
}

2b
function reverseArrayInPlace(arrayName){
var placeholder = 0;
var counter = 0
for(var i=0; i<arrayName.length; i++){
placeholder = arrayName.pop();
arrayName.splice(counter, 0, placeholder);
counter ++;
}
return arrayName
}

2c
In my code, reverseArrayInPlace has the side effect of altering the original array and is probably less useful in a program. However, because it does not involve the scanning and creation of a new array in memory, it might be faster.

Here is my code that combined both exercises:

var num = [];
function range(start,end, step){
var total = end - start;

        if(total <0 ){
          total = total * (-1); //this is to deal with negative step if it's used. Tried not to use any function here. 
        }
        var s = step;
        var nextnum = start;
        var i=0;
       while (i<=total){
         num.push(nextnum); 
          nextnum += s;
          i++;
        }
      }
      range(5,1,-1);
      console.log(num);

      var reversenum = [];
      var j;

      for (j=num.length; j>0; j--){
        reversenum.push(num[j-1]); //add into new array by referring to the reversed index. 
      }
      console.log(reversenum);
1 Like

Sum of a Range Exercise

function range(start,end, pace = 1){
  var list = [];

  if(start<end){
    for(var counter = start; counter <= end ; counter += pace){
        list.push(parseInt(counter));
    }
  }
  else{
    for(var counter = start; counter >= end ; counter += pace){
        list.push(parseInt(counter));
    }
  }
  console.log(list);
}

function sum_arr(array){

  let total = 0;

  for(var counter = 0; counter < array.length; counter ++){
    total += array[counter];
  }

  document.write(total);
  console.log(total);
}

Reversing an Array Exercise

function reverseArray(array){
  
  var newArray = [];
  for(var counter = (array.length-1); counter >= 0; counter -- ){
    newArray.push(array[counter]);
  }
  document.write(newArray);
}

function reverseArrayInPlace(array){
    for (var counter = 0; counter < array.length; counter++) {
        array.unshift(array.splice(counter, 1)[0]);
    }
  document.write(array);
}
1 Like

My solution to “The Sum of a range” exercise:

  <script>

  function getRangeArray(start, end, step=1) {
    let rangeArray = [];
    let elementNum = 0;

// Code before handling negative steps (commented out)
// for (num = start; num <= end; num+= step) {
// rangeArray[elementNum] = num;
// elementNum++;
// };

// Amended code to cater for negative steps

      const numOfElements = Math.floor( Math.abs( (start-end)/step ) + 1 );
      console.log("Num of Elements = ", numOfElements);
      for (num = start; elementNum < numOfElements; num+= step) {
        rangeArray[elementNum] = num;
        elementNum++;
      };

    return rangeArray;
  }

  function sumRangeArray( rangeArray ) {
    total = 0;
    for(i=0; i<rangeArray.length; i++) {
      total += rangeArray[i];
    };
    return total;
  };

  let myArray = getRangeArray(1, 10);
  console.log( myArray );
  console.log("Total:" + sumRangeArray( myArray ));

  let myArray2 = getRangeArray(1, 10, 2);
  console.log( myArray2 );
  console.log("Total:" + sumRangeArray( myArray2 ));

  let myArray3 = getRangeArray(5, 2, -1);
  console.log( myArray3 );
  console.log("Total:" + sumRangeArray( myArray3 ));

  </script>

Console output:
Num of Elements = 10
Sum of a range.html:62 (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sum of a range.html:63 Total:55
Sum of a range.html:44 Num of Elements = 5
Sum of a range.html:66 (5) [1, 3, 5, 7, 9]
Sum of a range.html:67 Total:25
Sum of a range.html:44 Num of Elements = 4
Sum of a range.html:70 (4) [5, 4, 3, 2]
Sum of a range.html:71 Total:14

1 Like

My Reversing Array Solution

  function reverseArray( inputArray ) {
    let outputArray = [];

    for (let i = inputArray.length - 1; i >= 0; i--) {
      outputArray.push( inputArray[i]);
    }

    return outputArray;
  }


  function reverseArrayInPlace( inputArray ) {

    const lenArray = inputArray.length;
    const halfLenArray = Math.floor( lenArray / 2);
    let temp1 = "";
    let temp2 = "";

    for (let i = 0; i < halfLenArray; i++) {
      temp1 = inputArray[i];
      temp2 = inputArray[lenArray-1-i];
      console.log("temp1=", temp1, " temp2=", temp2);
      inputArray[i] = temp2;
      inputArray[lenArray-1-i] = temp1;
    }
  };

  var myArray = [ 1, 2, 3, 4, 5];
  console.log("myArray (initialised):", myArray)
  console.log("Call ReverseArray(myArray): ", reverseArray(myArray) );
  console.log("myArray (unchanged )= ", myArray);

  reverseArrayInPlace(myArray);
  console.log("Call reverseArrayInPlace(myArray).\nmyArray (reversed) = ", myArray);

Console output:
myArray (initialised): (5) [1, 2, 3, 4, 5]
Reversing an array.html:53 Call ReverseArray(myArray): (5) [5, 4, 3, 2, 1]
Reversing an array.html:54 myArray (unchanged )= (5) [1, 2, 3, 4, 5]
Reversing an array.html:45 temp1= 1 temp2= 5
Reversing an array.html:45 temp1= 2 temp2= 4
Reversing an array.html:57 Call reverseArrayInPlace(myArray).
myArray (reversed) = (5) [5, 4, 3, 2, 1]

2 Likes

/*

The sum of a range Exercise #1

*/

// Write Range Functions taking arg as start and corresponding

function arrayNumRange(startNum, endNum, step=1)
{
    numArray = [];
    console.log(numArray);

    if (startNum < endNum)
    {
      for (i = startNum; i < endNum +1; i = i + step)
      {
        numArray.push(i);
      }

    }
    else if (endNum < startNum)
    {
      for (i = startNum; i > endNum -1; i = i + step)
      {
        numArray.push(i);
      }
    }

    console.log(numArray);
}

arrayNumRange(5, 2, -1);


// <------------reverseArrayInPlace ---------->


arrayArgs = [10, 8, 7, 5, 3];
numArray = [];
revNumArray=[];
function reverseArrayInPlace(arrayArgs)
{
  for (i = arrayArgs.length -1; i + 1 > 0; i--)
  {

arrayArgs.splice((arrayArgs.length - 1- i), 0 , arrayArgs[arrayArgs.length-1]);
arrayArgs.pop();
  }


}

reverseArrayInPlace(arrayArgs);
console.log(arrayArgs);


function range(start, end, step = start < end ? 1 : -1) {
let array = [];

	if (step > 0) {
		for (let i = start; i <= end; i += step) array.push(i);
	} else {
		for (let i = start; i >= end; i += step) array.push(i);
	}
return array;
}

function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}

console.log(sum(range(2, 9)));

1 Like

Just for fun I added a bit of hand rolled test code that validates expected results and prints test results using jQuery.

E1 - Range, Sum
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <title>EJ CH4 E1</title>
    </head>
    <body>
        <h1>EJ CH4 E1 - The sum of a Range</h1>
        
        <script>
            function range(start, end) {
                let arr = [];
                for (let i=start;i <= end; i++) {
                    arr.push(i);
                }
                return arr;
            }

            function sum(arr) {
                let result = 0;
                for(let v of arr) {
                    result += v;
                }
                return result;
            }

            // test range
            let expected = [2, 3, 4]
            let result = range (2, 4);
            assertArray(result, expected, "range should include both the start and end points");

            expected = [3]
            result = range (3, 3);
            assertArray(result, expected, "should return a list of one if start and end are the same");

            expected = []
            result = range (4, 2);
            assertArray(result, expected, "should return and emply list if start is less than end");

            expected = [-3, -2, -1]
            result = range (-3, -1);
            assertArray(result, expected, "should handle negative numbers");

            // test sum
            expected = 6;
            result = sum([1, 2, 3]);
            assert(result, expected, "should sum each item and return the correct amount");

            expected = 0;
            result = sum([]);
            assert(result, expected, "should return zero for an emply list");

            expected = 55;
            result = sum(range(1, 10));
            assert(result, expected, "should sum the output of range()");

            function assertArray(actual, expected, message) {
                const result = arrayEquals(actual, expected);
                printResults(result, actual, expected, message);
            }
            
            function assert(actual, expected, message) {
                const result = (actual == expected);
                printResults(result, actual, expected, message);
            }

            function printResults(result, actual, expected, message) {
                let txtResult = "";
                if (result) {
                    txtResult = "PASSED"
                } else {
                    txtResult = "FAILED";
                }

                $("<p/>").text(`${txtResult}: ${message}, expected:${expected}, actual:${actual}`).appendTo($("body"));
            }

            function arrayEquals(a, b) {
                if (!a || !b || a.length != b.length) {
                    return false;
                }
                for(let i=0; i< a.length; i++) {
                    if (a[i] != b[i]) {
                        return false;
                    }                    
                }
                return true;
            }
        </script>
    </body>
</html>
E2 - Reversing a List
  • The “copy” solution just iterates through the array backwards and pushes each item into a new array.
  • The “in place” solution uses cursors at the beginning and end of the array then swaps them, moving the cursors inwards until they reach the center.
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <title>EJ CH4 E2</title>
    </head>
    <body>
        <h1>EJ CH4 E2 - Reversing an Array</h1>
        
        <script>
            function reverseArray(arr) {
                let r = [];
                for(let i=arr.length-1; i>=0; i--) {
                    r.push(arr[i]);
                }
                return r;
            }

            function reverseInPlace(arr) {
                for(let from=0, to=arr.length-1; from <= to; from++, to--) {
                    // swap
                    let temp = arr[to];
                    arr[to] = arr[from];
                    arr[from] = temp;
                }
                return arr;
            }


            // test reverseArray
            let toReverse = [1, 2, 3]
            let expected = [3, 2, 1]
            let result = reverseArray([1, 2, 3]);
            assertArray(result, expected, "should reverse the array");
            assert(result != toReverse, true, "should return a copy of the array");
            assertArray(toReverse, [1, 2, 3], "original array should contain the same items");

            // test reverseInPlace()
            let toReverseInPlace = [1, 2, 3]
            expected = [3, 2, 1]
            result = reverseInPlace(toReverseInPlace);
            assertArray(result, expected, "should reverse the array");
            assert(result, toReverseInPlace, "should be the same instance");

            expected = [3, 2]
            result = reverseInPlace([2, 3]);
            assertArray(result, expected, "should reverse the array (case length=2)");

            expected = [1]
            result = reverseInPlace([1]);
            assertArray(result, expected, "should reverse the array (case length=1)");

            expected = []
            result = reverseInPlace([]);
            assertArray(result, expected, "should return an empty list if supplied an empty list");

            function assertArray(actual, expected, message) {
                const result = arrayEquals(actual, expected);
                printResults(result, actual, expected, message);
            }
            
            function assert(actual, expected, message) {
                const result = (actual == expected);
                printResults(result, actual, expected, message);
            }

            function printResults(result, actual, expected, message) {
                let txtResult = "";
                if (result) {
                    txtResult = "PASSED"
                } else {
                    txtResult = "FAILED";
                }

                $("<p/>").text(`${txtResult}: ${message}, expected:${expected}, actual:${actual}`).appendTo($("body"));
            }

            function arrayEquals(a, b) {
                if (!a || !b || a.length != b.length) {
                    return false;
                }
                for(let i=0; i< a.length; i++) {
                    if (a[i] != b[i]) {
                        return false;
                    }                    
                }
                return true;
            }
        </script>
    </body>
</html>

Which variant do you expect to be useful in more situations?
Depends on what you’re doing, but it’s usually best practice to favour have functions that don’t mutate their inputs so the “copy” implementation is better.

Which one runs faster?
As implemented, the “reverse in place swap” solution would run faster as it will require n/2 iterations where the copy requires n. The copy solution also has to allocate memory and possibly resize the output array multiple times, where the “in place” solution just reuses the existing array.

2 Likes