在 javascript 中的任一方向循环遍历范围

Loop through range in either direction in javascript

我正在寻找实现以下目标的简化方法:

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

以下是我目前使用的modulus,但我想知道是否有进一步简化它的方法?

增加:

v = (v + 1) % total

减少:

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

增加的伪代码已经完全简化,但是,您可以通过以下两种方式之一简化减少的逻辑:

v = v ? v - 1 : x - 1

v = (v + x - 1) % x

前者是有效的,因为您知道递减量永远不需要被调制到 [0, x) 范围内,但后一种方法是首选,因为它避免了不必要的分支逻辑。

请记住,作为一种边缘情况,如果 x 超过 Number.MAX_SAFE_INTEGER 的一半 (2**53 - 1),第一种方法是唯一可行的方法不出所料。