“GPT-3 Random Sample Dump: JavaScript Tutorial”, GPT-32020-05-28 ()⁠:

[Sample from GPT-3; condensed paragraphs & formatting added for legibility inside popups, as the original plain text dumps strip the original HTML formatting of tutorials etc.]

Working with an example—rotating through an array For a number of years, I’ve been fascinated by the idea of writing code that can rotate through an array. Let’s say I have the following array of numbers:

var myNumbers = [1, 2, 3, 4, 5];

The following snippet of code would display the same numbers in reverse order:

for (var i = myNumbers.length - 1; i ≥ 0; i-- ) { console.log( myNumbers[i] ); }

What’s going on here?

We know that the index of an array can be used as a “pointer” to the location in memory that contains a particular item in an array. If the array myNumbers has five items, then myNumbers[0], myNumbers[1], myNumbers[2], myNumbers[3] and myNumbers[4] will point to the values 1, 2, 3, 4 and 5 respectively.

In the previous example, the code starts with the length of the array (5) and subtracts one from it. As we know that index 0 in an array contains the first item in the array, the previous code will execute the following steps: Take the length of the array (5) Subtract 1 (so we now have 4) Start at the index that contains the first item in the array (myNumbers[4] = 3) and run down the array until we reach the last item in the array (myNumbers[3] = 5) So the above code will end up displaying the items in the array in reverse order, starting at index 4 and working backwards to index 0. At this point, we have a good idea of how we can access the values in an array in a specific order, but how do we go the other way?

It would be great if we could simply use the same code as above, but add a “–” operator before the last number. That way, we could add a simple parameter to the code to control the range of numbers it will use. Unfortunately, we can’t do that. While JavaScript will happily work with , it will also happily take in code and convert it to −1, or the last number in an array. That’s not going to do us any good, as we want the code to be flexible enough that we can work with a number that we specify as the range of numbers.

So let’s look at a simple function that can give us the results we need.

function rotate(numbers, direction, number) { numbers.reverse(); numbers.push(number); numbers.unshift(number); };

The rotate function above has three parameters, and will rotate the values in the numbers array…