MikeMcl / decimal.js

An arbitrary-precision Decimal type for JavaScript
http://mikemcl.github.io/decimal.js
MIT License
6.35k stars 480 forks source link

Add structuredClone support #224

Open WinterSmileSB101 opened 1 year ago

WinterSmileSB101 commented 1 year ago

Decimal.js seems to not support structuredClone, this method will throw DataCloneError because of decimal instance contains a function(constructor ) due to this line code: https://github.com/MikeMcl/decimal.js/blob/master/decimal.js#L4294

xxxx
// Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
// which points to Object.
x.constructor = Decimal;
xxxx

Any plans to support it?

MikeMcl commented 1 year ago

No, no plans, and that line is essential.

Would I like to support structuredClone? Yes. Am I going to investigate this matter right now or in the near future? Probably not.

WinterSmileSB101 commented 1 year ago

OK, thanks.

ctsstc commented 1 year ago

Just landed here as structured clone is finally becoming the goto for deep cloning an object.

@WinterSmileSB101 what did you end up doing to get around this?

For now here's my painful "fix" that conforms to typing.

Here's a simple example without crazy nesting involved:

const { decimalOne, decimalTwo, ...withoutDecimals } = originalObject // originalObject satisfies SomeType
const newObjectWithoutDecimals = structuredClone(withoutDecimals)
const newObject: SomeType = {
  ...newObjectWithoutDecimals,
  decimalOne: new Decimal(decimalOne),
  decimaltwo: new Decimal(decimalTwo),
}