"increment number up to a value" 的编程习语

Programming idiom for "increment number up to a value"

我经常遇到需要 "loop" 一个数字的情况。也就是说,给定一个值 X,我需要将它递增到一个点,然后循环回到零。这通常会导致一些相当冗长的代码,其中包含很多 "plus 1"。是否有一个很好的单线或其他一些好的成语来做到这一点?

示例(为了方便使用 JS 轮播):

function cycle() {

    const $e = $('.a-carousel');
    const activeClass = 'active';

    var activeIndex = $e.find('.' + activeClass).removeClass(activeClass).index();
    if (activeIndex + 1 >= $e.children().length) {
        activeIndex = -1;
    }

    $e.children().eq(activeIndex + 1).addClass(activeClass);

}

我不知道这是否有专门的术语,但您的代码比需要的更冗长。你可以用一个增量和一个 if 检查来做到这一点。

(伪代码)

x = MinValue
Loop
    Increment x
    If x > MaxValue
        x = MinValue
    Do things with x

一般来说,一个值ki[=37=的循环后继 ] 在范围 k0, ..., kn-1定义为

下一个( ki ) = (ki - k0 + 1) mod n + k0

例如,

range = 3 ... 9
k0 = 3
n = 7

k    k-k0    k-k0+1    k-k0+1 mod n    k-k0+1 mod n + k0
------------------------------------------------------------
6     3        4           4            7
7     4        5           5            8
8     5        6           6            9
9     6        7           0            3
3     0        1           1            4
4     1        2           2            5
5     2        3           3            6