utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.BigNumOps = exports.chainPromises = void 0;
  4. const chainPromises = (lazyPromises, reducer = (lp1, lp2) => (p) => lp1(p).then(lp2), initialValue) => lazyPromises.reduce(reducer, p => Promise.resolve(p))(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 === 0) {
  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. if (high === 0)
  22. return low.toString();
  23. return `${high}${Math.abs(low).toString().padStart(15, '0')}`;
  24. };
  25. const bigNumCompare = (num1, num2) => Math.sign(Number(bigNumPlus(num1, num2.replace(/^([+-]?)(\d+)/, (_, $1, $2) => `${$1 === '-' ? '' : '-'}${$2}`))));
  26. const bigNumMin = (...nums) => {
  27. if (!nums || !nums.length)
  28. return undefined;
  29. let min = nums[0];
  30. for (let i = 1; i < nums.length; i++) {
  31. if (bigNumCompare(nums[i], min) < 0)
  32. min = nums[i];
  33. }
  34. return min;
  35. };
  36. const bigNumLShift = (num, by) => {
  37. if (by < 0)
  38. throw Error('cannot perform right shift');
  39. const at = Math.trunc((52 - by) / 10) * 3;
  40. const [high, low] = splitBigNumAt(num, at).map(n => n * Math.pow(2, by));
  41. return bigNumPlus(`${high}${'0'.repeat(at)}`, low.toString());
  42. };
  43. const parseBigNum = (str) => (/^-?\d+$/.exec(str) || [''])[0].replace(/^(-)?0*/, '$1');
  44. exports.BigNumOps = {
  45. splitAt: splitBigNumAt,
  46. plus: bigNumPlus,
  47. compare: bigNumCompare,
  48. min: bigNumMin,
  49. lShift: bigNumLShift,
  50. parse: parseBigNum,
  51. };
  52. //# sourceMappingURL=utils.js.map