RandInt-Getter

get a stochastic integer in range

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/430439/1074311/RandInt-Getter.js

  1. // ==UserScript==
  2. // @name RandInt-Getter
  3. // @namespace http://greasyfork.org/
  4. // @version 0.1
  5. // @description get a stochastic integer in range
  6. // @author Cosil.C
  7. // @grant unsafeWindow
  8. // @license GPLv3
  9. // ==/UserScript==
  10.  
  11. /**
  12. * @description get a stochastic integer in range
  13. * @param exp pattern: [|( -* \d+ , -* \d+ )|]
  14. * @returns a stochastic integer with type number in range
  15. */
  16. unsafeWindow.getRandInt = (exp) => {
  17. if ('string' != typeof exp) {
  18. throw 'Expression param error: the param inputed must be a string';
  19. }
  20. if (!/[\[\(]\s*-{0,1}\s*\d+\s*,\s*-{0,1}\s*\d+\s*[\]\)]/.test(exp)) {
  21. throw 'Expression syntax error';
  22. }
  23. let res;
  24. exp.replace(/([\[\(])\s*(-{0,1}\s*\d+)\s*,\s*(-{0,1}\s*\d+)\s*([\]\)])/g, (rs, $1, $2, $3, $4) => {
  25. let left = $1.charCodeAt(),
  26. min = parseInt($2.replace(/\s+/, '')),
  27. max = parseInt($3.replace(/\s+/, '')),
  28. right = $4.charCodeAt();
  29. if (min > max) {
  30. throw `Expression param error: cause ${min} > ${max}`;
  31. } else if (right - left == 1 && max <= min + 1) {
  32. throw `Expression param error: cause range is '(' and ')' but can't found any integer between ${min} and ${max}`;
  33. } else {
  34. res = min + Math.floor(Math.random() * (max - min + (right == left + 2 ? 1 : right == left + 1 ? -1 : 0))) + (left == 40 ? 1 : 0);
  35. }
  36. })
  37. return res;
  38. }