UNPKG

1.41 kBJavaScriptView Raw
1// This example demonstrates how you could integrate support for BigInt
2// in mathjs. It's just a proof of concept, for full support you will
3// have to defined more functions and define conversions from and to
4// other data types.
5
6const math = require('../../index')
7
8math.import({
9 name: 'BigInt',
10 path: 'type', // will be imported into math.type.BigInt
11 factory: (type, config, load, typed) => {
12 typed.addType({
13 name: 'BigInt',
14 test: (x) => typeof x === 'bigint' // eslint-disable-line
15 })
16
17 // we can also add conversions here from number or string to BigInt
18 // and vice versa using typed.addConversion(...)
19
20 return BigInt // eslint-disable-line
21 },
22
23 // disable lazy loading as this factory has side
24 // effects: it adds a type and a conversion.
25 lazy: false
26})
27
28math.import({
29 name: 'bigint',
30 factory: (type, config, load, typed) => {
31 return typed('bigint', {
32 'number | string ': (x) => BigInt(x) // eslint-disable-line
33 })
34 }
35})
36
37math.import({
38 name: 'add',
39 factory: (type, config, load, typed) => {
40 return typed('add', {
41 'BigInt, BigInt': (a, b) => a + b
42 })
43 }
44})
45
46math.import({
47 name: 'pow',
48 factory: (type, config, load, typed) => {
49 return typed('pow', {
50 'BigInt, BigInt': (a, b) => a ** b
51 })
52 }
53})
54
55console.log(math.eval('bigint(4349) + bigint(5249)'))
56console.log(math.eval('bigint(4349) ^ bigint(5249)'))