获取数字模数范围以使返回值位于最小范围值和最大范围值之间的正确方法是什么?

What is the correct way to get a number modulo range such that the returned value lies between the min and max range values?

我正在查看传单 js 代码。有一个 wrapNum 函数。

// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
// Returns the number `num` modulo `range` in such a way so it lies within
// `range[0]` and `range[1]`. The returned value will be always smaller than
// `range[1]` unless `includeMax` is set to `true`.
function wrapNum(x, range, includeMax) {
    var max = range[1],
        min = range[0],
        d = max - min;
    return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
}

因此,他们只是试图找到一个数字模数范围,以便该数字位于给定的最小 - 最大范围之间。

如果我写 ((x - min) % d) + min 而不是使用 ((x - min) % d + d) % d + min 表达式,那会不会遗漏任何被原始表达式覆盖的测试用例?

…will that miss any test case that is covered by original expression?

是的。对于小于范围最小值 x 的大多数值,您将得到不正确的值 range[0].

那是因为 % multiplicative operator returns 是余数,不是正确的模数,例如

-1 % 12

returns -1,而不是 1(参见 JavaScript % (modulo) gives a negative result for negative numbers)因此使用了复杂的:

((x - min) % d + d) % d

得到正确的模值。部分播放代码:

function wrapNum0(x, range, includeMax) {
  var max = range[1],
    min = range[0],
    d = max - min;
  return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
}

function wrapNum1(x, range, includeMax) {
  var max = range[1],
    min = range[0],
    d = max - min;
  return x === max && includeMax ? x : ((x - min) % d) + min;
}


function doCalc(form) {
  var num = +form.num.value;
  var range = form.range.value.split(',').map(Number);
  var includeMax = form.includeMax.checked;
  form.result0.value = wrapNum0(num, range, includeMax);
  form.result1.value = wrapNum1(num, range, includeMax);
}
<form onsubmit="event.preventDefault();doCalc(this); return false;">
  <input value="3" name="num">Value<br>
  <input value="5,10" name="range">Range (<em>min,max</em>)<br>
  <input type="checkbox" name="includeMax">Inclue max?<br>
  <input readonly name="result0">Original (wrapNum0)<br>
  <input readonly name="result1">Modified (wrapNum1)<br>
  <input type="reset"><button>Do calc</button>
</form>