RandInt-Getter

get a stochastic integer in range

当前为 2021-08-07 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/430439/957975/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. // @license GPL
  8. // ==/UserScript==
  9.  
  10.  
  11. document.defaultView.getRandInt = getRandInt;
  12.  
  13.  
  14. /**
  15. * @description get a stochastic integer in range
  16. * @param exp pattern: [|( -* \d+ , -* \d+ )|]
  17. * @returns a stochastic integer with type number in range
  18. */
  19. function getRandInt(exp) {
  20. if ('string' != typeof exp) {
  21. throw 'Expression param error: the param inputed must be a string';
  22. }
  23. if (!/[\[\(]\s*-{0,1}\s*\d+\s*,\s*-{0,1}\s*\d+\s*[\]\)]/.test(exp)) {
  24. throw 'Expression syntax error';
  25. }
  26. let res;
  27. exp.replace(/([\[\(])\s*(-{0,1}\s*\d+)\s*,\s*(-{0,1}\s*\d+)\s*([\]\)])/g, (rs, $1, $2, $3, $4) => {
  28. let left = $1.charCodeAt(),
  29. min = parseInt($2.replace(/\s+/, '')),
  30. max = parseInt($3.replace(/\s+/, '')),
  31. right = $4.charCodeAt();
  32. if (min > max) {
  33. throw `Expression param error: cause ${min} > ${max}`;
  34. } else if (right - left == 1 && max <= min + 1) {
  35. throw `Expression param error: cause range is '(' and ')' but can't found any integer between ${min} and ${max}`;
  36. } else {
  37. res = min + Math.floor(Math.random() * (max - min + (right == left + 2 ? 1 : right == left + 1 ? -1 : 0))) + (left == 40 ? 1 : 0);
  38. }
  39. })
  40. return res;
  41. }