Skip to main content

Random

Runtime: any — Node.js ≥ 22 or a modern browser

Random integers, floats, booleans, strings and array picks. All of it is Math.random — fast, seedless and not cryptographically secure — which makes it right for test fixtures, sampling, jitter and visuals, and wrong for tokens, session ids or anything an attacker would like to predict (use crypto.randomHex). Note the asymmetry: randomInt includes both bounds, randomFloat excludes its maximum.

Example​

import { randomElement, randomFloat, randomInt, randomString } from '@rtorcato/js-common/random'
import { sleep } from '@rtorcato/js-common/sleep'

// Test fixtures, sampling and jitter — never tokens or ids.
randomInt(1, 6) // 1–6, both bounds included
randomFloat(0, 1) // 0 ≤ n < 1, maximum excluded
randomElement(['red', 'green']) // one of them, or undefined for an empty array
randomString(8) // e.g. 'a7Kd0Pq2'

await sleep(randomInt(100, 400)) // retry jitter

Import​

import { randomBool, randomElement, randomFloat } from '@rtorcato/js-common/random'

Exports​

NameSummary
randomBoolReturns a random boolean value.
randomElementReturns a random element from an array.
randomFloatReturns a random float between min (inclusive) and max (exclusive).
randomIntReturns a random integer between min (inclusive) and max (inclusive).
randomStringReturns a random string of the given length using the given characters.

See also​

  • numbers — sum, average, clamp, roundTo
  • arrays — chunk, unique, compact and other array helpers
  • uuid — generate and validate UUIDs
  • crypto — hashing, HMAC, base64, random hex