1 function Big() {
2 "use strict";
3
4 // 把 '123' 分散为 [3, 2, 1]
5 function getDigitList(n) {
6 return (n + "")
7 .split("")
8 .reverse()
9 .map((d) => +d);
10 }
11
12 function add(n0, n) {
13 if (typeof n0 != "string" || typeof n != "string") {
14 throw Error("Please enter a string");
15 }
16
17 n0 = getDigitList(n0);
18 n = getDigitList(n);
19 let max = Math.max(n0.length, n.length),
20 _high = 0,
21 digitList = [];
22 for (let i = 0; i < max; i++) {
23 const [low, high = 0] = getDigitList((n0[i] || 0) + (n[i] || 0) + _high);
24 digitList.push(low);
25 _high = high;
26 }
27 if (_high) {
28 digitList.push(_high);
29 }
30 return digitList.reverse().join("");
31 }
32
33 function mul(n0, n) {
34 if (typeof n0 != "string" || typeof n != "string") {
35 throw Error("Please enter a string");
36 }
37
38 n0 = getDigitList(n0);
39 n = getDigitList(n);
40 const D1 = n0.reduce(function (D1, d1, i) {
41 let _high = 0;
42 let D2 = n.reduce(function (D2, d2) {
43 const [low, high = 0] = getDigitList(d1 * d2 + _high);
44 D2.push(low);
45 _high = high;
46 return D2;
47 }, new Array(i).fill(0));
48 _high && D2.push(_high);
49 return add(D1, D2.reverse().join(""));
50 }, "");
51
52 return D1;
53 }
54
55 this.add = add;
56 this.mul = mul;
57 }