utils.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.BigNumOps = exports.chainPromises = void 0;
  4. exports.chainPromises = (promises, reducer = (p1, p2) => p1.then(() => p2), initialValue) => promises.reduce(reducer, Promise.resolve(initialValue));
  5. const splitBigNumAt = (num, at) => num.replace(RegExp(String.raw `^([+-]?)(\d+)(\d{${at}})$`), '$1$2,$1$3')
  6. .replace(/^([^,]*)$/, '0,$1').split(',')
  7. .map(Number);
  8. const bigNumPlus = (num1, num2) => {
  9. let [high, low] = [splitBigNumAt(num1, 15), splitBigNumAt(num2, 15)]
  10. .reduce((a, b) => [a[0] + b[0], a[1] + b[1]]);
  11. const [highSign, lowSign] = [high, low].map(Math.sign);
  12. if (highSign === 0)
  13. return low.toString();
  14. if (highSign !== lowSign) {
  15. [high, low] = [high - highSign, low - lowSign * Math.pow(10, 15)];
  16. }
  17. else {
  18. [high, low] = [high + Math.trunc(low / Math.pow(10, 15)), low % Math.pow(10, 15)];
  19. }
  20. if (high === 0)
  21. return low.toString();
  22. return `${high}${Math.abs(low).toString().padStart(15, '0')}`;
  23. };
  24. const bigNumCompare = (num1, num2) => Math.sign(Number(bigNumPlus(num1, num2.replace(/^([+-]?)(\d+)/, (_, $1, $2) => `${$1 === '-' ? '' : '-'}${$2}`))));
  25. const bigNumMin = (...nums) => {
  26. if (!nums || !nums.length)
  27. return undefined;
  28. let min = nums[0];
  29. for (let i = 1; i < nums.length; i++) {
  30. if (bigNumCompare(nums[i], min) < 0)
  31. min = nums[i];
  32. }
  33. return min;
  34. };
  35. const bigNumLShift = (num, by) => {
  36. if (by < 0)
  37. throw Error('cannot perform right shift');
  38. const at = Math.trunc((52 - by) / 10) * 3;
  39. const [high, low] = splitBigNumAt(num, at).map(n => n * Math.pow(2, by));
  40. return bigNumPlus(high + '0'.repeat(at), low.toString());
  41. };
  42. const parseBigNum = (str) => ((str === null || str === void 0 ? void 0 : str.match(/^-?\d+$/)) || [''])[0].replace(/^(-)?0*/, '$1');
  43. exports.BigNumOps = {
  44. splitAt: splitBigNumAt,
  45. plus: bigNumPlus,
  46. compare: bigNumCompare,
  47. min: bigNumMin,
  48. lShift: bigNumLShift,
  49. parse: parseBigNum,
  50. };