Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow object literals without _isBignumber flag #318

Closed
wants to merge 1 commit into from

Conversation

florianbepunkt
Copy link

Fixes Rehydration after structural cloning #317.

An obj { s: 1, e: -2, c: [ 50 ] } is not a BigNumber, hence BigNumber.isBigNumber(obj) is false, but you can construct a BigNumber from it: new BigNumber(obj).

This simplifies serialization/deserialization, since BigNumber values can be sent over the wire/inter process communication.

const someFn = (valueThatMightBeSerializedOrNot: BigNumber) => new BigNumber(valueThatMightBeSerializedOrNot).plus(1);
const bnValue = new BigNumber(1);
const fromJsonValue = JSON.parse(JSON.stringify(bnValue);

assert.strictEqual(someFn(bnValue).toString(), someFn(fromJsonValue).toString())

Fixes Rehydration after structural cloning MikeMcl#317.
@MikeMcl
Copy link
Owner

MikeMcl commented Dec 4, 2022

I remain reluctant to replace the _isBigNumber === true test with your suggested typeof triplet on probably the hottest code path in the library (regardless of whether or not it would seem to make any significant difference in performance).

Deserialization after structured cloning is pretty straightforward as it is:

const serialize = bn => JSON.stringify(structuredClone(bn));
const deserialize = json => new BigNumber({ _isBigNumber: true, ...JSON.parse(json) });

const a = new BigNumber('1.23');
const b = deserialize(serialize(a));

console.log(a.eq(b));    // true

I apologise for the late response, and thank you for your efforts.

On second thoughts, maybe I'll add a BigNumber.fromObject method as suggested by #245. Anyway, I'll leave this open for now...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants