Civet icon indicating copy to clipboard operation
Civet copied to clipboard

BigInt ranges work in for/of, but not as values

Open bbrk24 opened this issue 1 year ago • 2 comments
trafficstars

for i of [1n..28n]
  ;

i is in [1n..28n]
// vvv
for (let i1 = 1n; i1 <= 28n; ++i1) {
  const i = i1;
}

((s, e) => {
  let step = e > s ? 1 : -1;
  return Array.from({ length: Math.abs(e - s) + 1 }, (_, i) => s + i * step);
})(1n, 28n).includes(i);

The latter will throw a TypeError at runtime due to the + 1 Math.abs.

bbrk24 avatar Nov 16 '24 15:11 bbrk24

Potential translation that works for both bigint and number:

((s, e) => {
  let step = e > s ? 1 : -1;
  const makeStep = typeof s == 'bigint'
    ? (i) => BigInt(step * i)
    : (i) => step * i;
  return Array.from({ length: Math.abs(Number(e - s)) + 1 }, (_, i) => s + makeStep(i));
})

bbrk24 avatar Nov 16 '24 17:11 bbrk24

We may also be able to convert is in [...] with range literals into comparison operations.

STRd6 avatar Apr 14 '25 22:04 STRd6