cluster1
cluster1

Reputation: 5674

Endlessly moving through an array backwards

I've got to be able moving through an array forwards and backwards. Endlessly and without getting an index out of bounds-exception.

For moving forward I've known an elegant way using the modulo-operator. For the backwards moving I've had to figure out something myself.

Here's my solution:

const inc = document.getElementById("inc");
const dec = document.getElementById("dec");
const arr = ["One", "Two", "Three", "Four", "Five", "Six"];
let i = 0;

inc.addEventListener("click", () => {
  i = (i + 1) % arr.length;

  console.log(arr[i]);
});

dec.addEventListener("click", () => {
  i = i - 1;

  if (i === -1) {
    i = arr.length - 1;
  }

  console.log(arr[i]);
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <button id="inc">Inc</button>
  <button id="dec">Dec</button>
</body>

</html>

It works. But is there a more elegant solution for moving backwards?

So that one can get rid of this ugly if-check.

Upvotes: 6

Views: 325

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

Yes, you could use a single formula for both forwards and backwards by creating a common function move and pass the step as parameter.

i = (i + step + arr.length ) % arr.length;

let arr = ["One", "Two", "Three", "Four", "Five", "Six"] , i = 0
function move(step){
  i = (i + step + arr.length ) % arr.length;
  console.log(arr[i]);
}
<button id="inc" onclick="move(1)">Inc</button>
<button id="dec" onclick="move(-1)">Dec</button>

Upvotes: 5

Pointy
Pointy

Reputation: 413717

You can still use the modulus operator. To go backwards, it'd be

i = (i - 1 + array.length) % array.length;

When i is 0, the partial result will be (0 - 1 + array.length), which is array.length - 1.

For any value greater than 0 but less than array.length, the modulus operator maps the value greater than array.length to the correct index in range.

Upvotes: 6

Related Questions