GoogleChromeLabs / jsbi

JSBI is a pure-JavaScript implementation of the official ECMAScript BigInt proposal.
https://v8.dev/features/bigint#polyfilling-transpiling
Apache License 2.0
919 stars 68 forks source link

Error: Convert JSBI instances to native numbers using `toNumber`. #88

Closed pavbro closed 2 years ago

pavbro commented 2 years ago

Version 4.2.0 Mac M1 and Ubuntu 20

JSBI.BigInt(2) ** JSBI.BigInt(2)

Error: Convert JSBI instances to native numbers using toNumber.

And if JSBI.exponentiate(2, 2)

TypeError: _.__unsignedDigit is not a function

12wrigja commented 2 years ago
JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(2))

is the right way to do this. Exponentiate does not accept numbers, only JSBI instances: https://github.com/GoogleChromeLabs/jsbi/blob/62ed38c09f3e272b8c3d5c3f25e40f8f331d021b/lib/jsbi.ts#L166

alxroyer commented 1 year ago

@12wrigja Just to share about my latest experiments with jsbi.

Here is the kind of wrapper I've recently set around JSBI.multiply() in order to make the things work in a full app (with third party libraries) with 'jsbi@4.3.0':

const _initialJsbiMultiply = jsbi.multiply;
/**
 * Wrap `JSBI.multiply()` in order to control its input parameters: convert simple numbers to big integers.
 */
jsbi.multiply = (x, y) => {
    // According to https://github.com/GoogleChromeLabs/jsbi/blob/main/jsbi.d.ts, `x` and `y` should be `JSBI` objects.
    // Add implicit conversions in case of simple numbers.
    if (typeof(x) === "number") {
        x = jsbi.BigInt(x);
    }
    if (typeof(y) === "number") {
        y = jsbi.BigInt(y);
    }

    // Eventually call the original implementation.
    return _initialJsbiMultiply(x, y);
};

What if JSBI.exponentiate(), JSBI.multiply(), ... would accept number values as input parameters?

static exponentiate(x: JSBI | number, y: JSBI | number): JSBI;
static multiply(x: JSBI | number, y: JSBI | number): JSBI;
jakobkummerow commented 1 year ago

Real BigInts don't allow mixing with Numbers (e.g. 1 + 2n throws a TypeError), so JSBI shouldn't allow that either.

JSBI is very intentionally designed to be compiled away eventually, so its behavior must be a subset of what real BigInts allow.

Of course you can add automatic conversion wrappers to your code if you think that's a good idea, but we won't add them to JSBI.

alxroyer commented 1 year ago

Ok, thanks for the explanation.