`io.random()` is identical to `Math.random()` when called without options but ensures your random numbers are not regenerated on resume or retry. It will return a pseudo-random floating-point number between optional `min` (default: 0, inclusive) and `max` (default: 1, exclusive). Can optionally `rou
(
cacheKey: string | any[],
{
min = 0,
max = 1,
round = false,
}: {
min?: number;
max?: number;
round?: boolean;
} = {}
)
| 278 | * @param round Controls rounding to the nearest integer. Any `max` integer will become inclusive when enabled. Rounding with floating-point bounds may cause unexpected skew and boundary inclusivity. |
| 279 | */ |
| 280 | async random( |
| 281 | cacheKey: string | any[], |
| 282 | { |
| 283 | min = 0, |
| 284 | max = 1, |
| 285 | round = false, |
| 286 | }: { |
| 287 | min?: number; |
| 288 | max?: number; |
| 289 | round?: boolean; |
| 290 | } = {} |
| 291 | ) { |
| 292 | return await this.runTask( |
| 293 | cacheKey, |
| 294 | async (task) => { |
| 295 | if (min > max) { |
| 296 | throw new Error( |
| 297 | `Lower bound can't be higher than upper bound - min: ${min}, max: ${max}` |
| 298 | ); |
| 299 | } |
| 300 | |
| 301 | if (min === max) { |
| 302 | await this.logger.warn( |
| 303 | `Lower and upper bounds are identical. The return value is not random and will always be: ${min}` |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | const withinBounds = (max - min) * Math.random() + min; |
| 308 | |
| 309 | if (!round) { |
| 310 | return withinBounds; |
| 311 | } |
| 312 | |
| 313 | if (!Number.isInteger(min) || !Number.isInteger(max)) { |
| 314 | await this.logger.warn( |
| 315 | "Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity." |
| 316 | ); |
| 317 | } |
| 318 | |
| 319 | const rounded = Math.round(withinBounds); |
| 320 | |
| 321 | return rounded; |
| 322 | }, |
| 323 | { |
| 324 | name: "random", |
| 325 | icon: "dice-5-filled", |
| 326 | params: { min, max, round }, |
| 327 | properties: [ |
| 328 | ...(min === 0 |
| 329 | ? [] |
| 330 | : [ |
| 331 | { |
| 332 | label: "min", |
| 333 | text: String(min), |
| 334 | }, |
| 335 | ]), |
| 336 | ...(max === 1 |
| 337 | ? [] |
no test coverage detected