Nico
Nico

Reputation: 221

Loop through range in either direction in javascript

I'm looking for a simplified way of achieving the following goal:

Loop through the range 0 to x in either direction, where x is any positive number.

The following is what I have so far using modulus, but I'm wondering if there is a way to simplify it even further?

Increase:

v = (v + 1) % total

Decrease:

v = v ? (v - 1) % x : x - 1

Upvotes: 0

Views: 160

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51756

The increase pseudo-code is already fully simplified, however, you can simplify the logic for your decrease in one of two ways:

v = v ? v - 1 : x - 1

or

v = (v + x - 1) % x

The former is valid because you know the decrement will never need to be modulated to be in the range [0, x), but the latter approach is preferred because it avoids unnecessary branching logic.

Keep in mind though, as an edge-case, if x is over half of Number.MAX_SAFE_INTEGER (2**53 - 1), the first approach is the only one that will work as expected.

Upvotes: 1

Related Questions