ranges.js
View source code here on GitHub!
This module directly ports some of the logic found in Python's range
.
- ranges.rangeEntry3(start, idx, step)
Returns the number at position
idx
in a range starting atstart
and iterating bystep
.- Arguments:
start (number)
idx (number)
step (number)
- Returns:
number --
- ranges.rangeEntry4(start, stop, idx, step)
Returns the number at position
idx
in the range [start
,stop
) and iterating bystep
.- Arguments:
start (number)
stop (number)
idx (number)
step (number)
- Returns:
number|undefined --
1/**
2 * Returns the number at position ``idx`` in a range starting at ``start`` and iterating by ``step``.
3 * @param {number} start
4 * @param {number} idx
5 * @param {number} step
6 * @return {number}
7 */
8function rangeEntry3(start, idx, step) {
9 return start + idx * step;
10}
11exports.rangeEntry3 = rangeEntry3;
12
13/**
14 * Returns the number at position ``idx`` in the range [``start``, ``stop``) and iterating by ``step``.
15 * @param {number} start
16 * @param {number} stop
17 * @param {number} idx
18 * @param {number} step
19 * @return {number | undefined}
20 */
21function rangeEntry4(start, stop, idx, step) {
22 let length = 0;
23 if (step > 0 && start < stop) {
24 length = Math.floor(1 + (stop - 1 - start) / step);
25 } else if (step < 0 && start > stop) {
26 length = Math.floor(1 + (start - 1 - stop) / (-step));
27 }
28 if (idx < 0) {
29 idx = length + idx;
30 }
31 if (idx < 0 || idx >= length) {
32 return undefined;
33 }
34 return rangeEntry3(start, idx, step);
35}
36exports.rangeEntry4 = rangeEntry4;