|
| 1 | +/** |
| 2 | + * Builds a randrange function given a randint function. |
| 3 | + * |
| 4 | + * @param {Function} randint The randint function. |
| 5 | + * @return {Function} The choice function. |
| 6 | + */ |
| 7 | +const _randrange = (randint) => { |
| 8 | + /** |
| 9 | + * Pick an element from range(start, stop, step) uniformly at random. |
| 10 | + * |
| 11 | + * Return an element from range(start, stop, step) selected uniformly at random. |
| 12 | + * If step is positive, this set corresponds to |
| 13 | + * {x: x in [start, stop[ AND x % step = 0}. |
| 14 | + * If step is negative, the range has to be given in reverse order, that is, |
| 15 | + * largest value first, smallest value second. Both the starting value and the |
| 16 | + * step value are optional. By default the starting value is <code>0</code>. |
| 17 | + * The default for the step value is <code>1</code>. |
| 18 | + * |
| 19 | + * TODO: Handle empty ranges. |
| 20 | + * |
| 21 | + * @param {number} [start=0] - The starting value. |
| 22 | + * @param {number} stop - The stopping value. |
| 23 | + * @param {number} [step=1] - The step value. |
| 24 | + * @return {number} The picked element. |
| 25 | + */ |
| 26 | + const randrange = (start, stop, step) => { |
| 27 | + if (stop === undefined) return randint(0, start); |
| 28 | + if (step === undefined) step = 1; |
| 29 | + |
| 30 | + if (stop >= start) { |
| 31 | + return start + step * randint(0, Math.floor((stop - start) / step)); |
| 32 | + } |
| 33 | + |
| 34 | + return start + step * randint(0, Math.floor((start - stop) / -step)); |
| 35 | + }; |
| 36 | + |
| 37 | + return randrange; |
| 38 | +}; |
| 39 | + |
| 40 | +export default _randrange; |
0 commit comments