utils.js 2.0 KB

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