Collection · 17 utilities

Random utilities

Random values for games, sampling and fixtures — and, where the value is a secret, the Web Crypto API instead of Math.random.

Generate a random boolean

Return true or false with equal probability.

function randomBoolean() { return Math.random() < 0.5; }random

Generate a random hex color

Return a #rrggbb color from 24 random bits.

function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart…random

Generate a random IP address

Return a random IPv4 address from the ranges reserved for documentation.

function randomDocumentationIp() { const networks = ['192.0.2', '198.51.100', '203.0.113']; ret…random

Generate a random sign

Return 1 or -1 with equal probability.

function randomSign() { return Math.random() < 0.5 ? -1 : 1; }random

Generate a random string from given characters

Draw characters from an alphabet with a cryptographic generator, without bias.

function randomString(length, alphabet) { if (alphabet.length < 2 || alphabet.length > 256) thr…random

Generate a random string with given length

Return a lowercase Base32 identifier from a cryptographic generator.

function randomId(length) { const alphabet = '0123456789abcdefghjkmnpqrstvwxyz'; return Array.f…random

Generate a random UUID

Return a version 4 UUID from the platform’s cryptographic generator.

function uuid() { return crypto.randomUUID(); }random

Get a random item from an array

Return one item at a random index.

function randomItem(values) { return values[Math.floor(Math.random() * values.length)]; }random

Get random items of an array

Return count distinct items in random order.

function randomItems(values, count) { const pool = [...values]; for (let i = pool.length - 1; i…random

Pick a random property of an object

Return one of the object’s own enumerable keys.

function randomKey(object) { const keys = Object.keys(object); return keys[Math.floor(Math.rand…random

Pick random lines from a text document

Split text into lines and return count of them in random order.

function randomLines(text, count) { const lines = text.split(/\r?\n/); for (let i = lines.lengt…random

These functions take callbacks, the DOM or the runtime, so each page shows usage that the tests execute. Read the limits before using one in an application.

Type two or more characters. Try “duplicate”, “webhook” or “retry”.