UNPKG

1.38 kBJavaScriptView Raw
1import Decimal from 'decimal.js'
2import { factory } from '../../utils/factory'
3
4const name = 'BigNumber'
5const dependencies = ['?on', 'config']
6
7export const createBigNumberClass = /* #__PURE__ */ factory(name, dependencies, ({ on, config }) => {
8 const BigNumber = Decimal.clone({ precision: config.precision })
9
10 /**
11 * Attach type information
12 */
13 BigNumber.prototype.type = 'BigNumber'
14 BigNumber.prototype.isBigNumber = true
15
16 /**
17 * Get a JSON representation of a BigNumber containing
18 * type information
19 * @returns {Object} Returns a JSON object structured as:
20 * `{"mathjs": "BigNumber", "value": "0.2"}`
21 */
22 BigNumber.prototype.toJSON = function () {
23 return {
24 mathjs: 'BigNumber',
25 value: this.toString()
26 }
27 }
28
29 /**
30 * Instantiate a BigNumber from a JSON object
31 * @param {Object} json a JSON object structured as:
32 * `{"mathjs": "BigNumber", "value": "0.2"}`
33 * @return {BigNumber}
34 */
35 BigNumber.fromJSON = function (json) {
36 return new BigNumber(json.value)
37 }
38
39 if (on) {
40 // listen for changed in the configuration, automatically apply changed precision
41 on('config', function (curr, prev) {
42 if (curr.precision !== prev.precision) {
43 BigNumber.config({ precision: curr.precision })
44 }
45 })
46 }
47
48 return BigNumber
49}, { isClass: true })