utils.js 2.5 KB

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