utils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Arr = 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 chunkArray = (arr, size) => {
  7. const noOfChunks = Math.ceil(size && arr.length / size);
  8. const res = Array(noOfChunks);
  9. for (let [i, j] = [0, 0]; i < noOfChunks; i++) {
  10. res[i] = arr.slice(j, j += size);
  11. }
  12. return res;
  13. };
  14. const splitBigNumAt = (num, at) => num.replace(RegExp(String.raw `^([+-]?)(\d+)(\d{${at}})$`), '$1$2,$1$3')
  15. .replace(/^([^,]*)$/, '0,$1').split(',')
  16. .map(Number);
  17. const bigNumPlus = (num1, num2) => {
  18. let [high, low] = [splitBigNumAt(num1, 15), splitBigNumAt(num2, 15)]
  19. .reduce((a, b) => [a[0] + b[0], a[1] + b[1]]);
  20. const [highSign, lowSign] = [high, low].map(Math.sign);
  21. if (highSign === 0)
  22. return low.toString();
  23. if (highSign + lowSign === 0) {
  24. [high, low] = [high - highSign, low - lowSign * Math.pow(10, 15)];
  25. }
  26. else {
  27. [high, low] = [high + Math.trunc(low / Math.pow(10, 15)), low % Math.pow(10, 15)];
  28. }
  29. if (high === 0)
  30. return low.toString();
  31. return `${high}${Math.abs(low).toString().padStart(15, '0')}`;
  32. };
  33. const bigNumCompare = (num1, num2) => Math.sign(Number(bigNumPlus(num1, num2.replace(/^([+-]?)(\d+)/, (_, $1, $2) => `${$1 === '-' ? '' : '-'}${$2}`))));
  34. const bigNumMin = (...nums) => {
  35. if (!nums || !nums.length)
  36. return undefined;
  37. let min = nums[0];
  38. for (let i = 1; i < nums.length; i++) {
  39. if (bigNumCompare(nums[i], min) < 0)
  40. min = nums[i];
  41. }
  42. return min;
  43. };
  44. const bigNumLShift = (num, by) => {
  45. if (by < 0)
  46. throw Error('cannot perform right shift');
  47. const at = Math.trunc((52 - by) / 10) * 3;
  48. const [high, low] = splitBigNumAt(num, at).map(n => n * Math.pow(2, by));
  49. return bigNumPlus(`${high}${'0'.repeat(at)}`, low.toString());
  50. };
  51. const parseBigNum = (str) => (/^-?\d+$/.exec(str) || [''])[0].replace(/^(-)?0*/, '$1');
  52. exports.BigNumOps = {
  53. splitAt: splitBigNumAt,
  54. plus: bigNumPlus,
  55. compare: bigNumCompare,
  56. min: bigNumMin,
  57. lShift: bigNumLShift,
  58. parse: parseBigNum,
  59. };
  60. exports.Arr = { chunk: chunkArray };