0

I'm currently extending the Array.prototype to include a simple 'pointer' system, as I can move through there on several different spots without looping.

Array.prototype.current = 0;

This pointer can move both forwards and backwards through the array, using the following method to go forwards:

Array.prototype.next = function () {
   return this[(this.current + 1) % this.length];
};

This line of code allows the pointer to be increased by one, unless it reaches the final index, in which case if it is increased again, it will return to index 0 instead of going out of bounds (because of the modulo).

However, now I want the exact same, but when decreasing the pointer instead. This would create something similar, i.e.:

Array.prototype.prev = function () {
   return this[(this.current - 1) /* similar to modulo here */];
};

What I want here is that the pointer gets decreased by 1 under any normal circumstance. However, if the pointer was 0, it needs to go back to the last index of the array instead, so effectively reverse looping around. But, I want this with as minimal code as possible, like the modulo solution for increasing the pointer but looping it back to start if it reaches the end.

Is there a short-hand solution like the modulo solution possible for this?

EDIT In response to the duplication flag. The referenced question and answers there indeed do apply to my question, so I understand the marking. However, it does not reference such a case of looping a list backwards and looping from front to back like this case (without branches, that is). After a considerable amount of time I hadn't run into this solution, so I'd think this question would result in positive impact for others running into a similar issue like mine.

Toastyblast
  • 140
  • 7

1 Answers1

3

you can try this

Array.prototype.prev = function () {
   return this[(this.current - 1 + this.length) % this.length] 
};
ashish singh
  • 6,526
  • 2
  • 15
  • 35