Feature request: parseInt for bigint (convert any string of any radix)

I was thinking of adding a function that is similar to parseint(string, radix) but works with bigint. So far according to mozilla, bigint() only works with binary (0b), decimal, and hex(0x). Something like parseBigInt(string, radix).

Interesting feature, and curious what's the specific use case for this function? A string stored a number that's larger than 2^53-1 seems taking much memory, except for the radix are really possible to be large enough, too.

Otherwise, an alternative for converting a valid integer string to BigInt type could be:

BigInt(parseInt('12345', radix)) // 12345n

That has a potential of losing precision if the string is a large number. I am suggesting a function that converts a string with any radix to bigint without losing precision.

You could try to make it so up to radix=16 is allowed to convert a string to bigint.

See https://github.com/tc39/proposal-number-fromstring

Thanks!

Sorry to rehash an old post, but I also have the use case to support base-36 decoding into a BigInt. I see the link above for fromString hasn't moved in a while. Does anyone know an unofficial implementation of a parseBigInt function?

I figured out an implementation:

const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const base = 36;
const chars = Array.from(s).reverse();
return chars.reduce((c, n, i) => {
  const pos = BigInt(alphabet.indexOf(n));
  return c + (pos * BigInt(Math.pow(base, i)));
}, 0n);

Math.pow(base, i) will lose precision quickly. Math.pow(36, 17) != 36n ** 17n. Good news is you don't need to use exponentiation at all if you don't reverse the input.

function parse(str, base = 36n) {
  return Array.prototype.reduce.call(str, (acc, digit) => {
    const pos = BigInt(alphabet.indexOf(digit));
    return acc * base + pos;
  }, 0n);
}
2 Likes

Nice, much cleaner. I overlooked the Math.pow issue. Thanks!

And if you did need to reverse the input, you could just use .reduceRight.