@hyperfrontend/random-generator-utilsView on npm →API Reference →

@hyperfrontend/random-generator-utils

Statistical random distributions and UUID generation for simulations, testing, and procedural content.

What is @hyperfrontend/random-generator-utils?

@hyperfrontend/random-generator-utils provides random number generators beyond JavaScript's basic Math.random(), focusing on statistical distributions used in simulations, load testing, and procedural generation. It includes Gaussian (normal), exponential, power law, and logarithmic distributions, plus UUID v4 generation and seeded pseudo-random functions.

Unlike cryptographic random generators (like Web Crypto API), these utilities prioritize reproducibility and distribution shapes over security. The seeded pseudo-random generator allows deterministic sequences for testing, while statistical distributions model real-world phenomena like response times, user behavior, and natural variation.

Key Features

  • Statistical distributions: Gaussian, exponential, power law, logarithmic, uniform
  • UUID v4 generation with validation (uuidV4(), isUuidV4())
  • Seeded pseudo-random for reproducible sequences in tests
  • Time-based seeding for pseudo-random variations
  • Zero dependencies - Self-contained implementation with no third-party runtime dependencies
  • Pure functions for functional composition

Architecture Highlights

All generators use Math.random() as the entropy source, transformed mathematically to match target distributions. Gaussian uses Box-Muller transform, exponential uses inverse transform sampling. Seeded generator uses sine function for deterministic output.

Why Use @hyperfrontend/random-generator-utils?

Realistic Load Testing and Simulations

Math.random() generates uniform distributions, but real-world events follow different patterns. User response times cluster around an average (Gaussian), server failures often show exponential decay, and popularity follows power law distributions (80/20 rule). These generators let you model realistic scenarios in load tests and simulations.

Reproducible Pseudo-Random Sequences for Testing

The seeded pseudo-random generator (randomPseudo()) produces deterministic output from a numeric seed. This enables reproducible test scenarios, snapshot testing with "random" data, and debugging flaky tests caused by true randomness. Time-based seeding (randomPseudoTimeBased()) provides daily or hourly variations while maintaining reproducibility within those windows.

UUID Generation Without External Dependencies

Many projects pull in the uuid package (500KB+) just for v4 UUIDs. This library provides a lightweight alternative with both generation and validation. Ideal for test fixtures, trace IDs, or non-security-critical unique identifiers without bloating bundles.

Functional Composition for Data Pipelines

All generators are pure functions accepting parameters and returning numbers. This makes them composable in data generation pipelines, Array methods (Array.from({ length: 100 }, () => randomGaussian(0, 100))), or streaming data generators for charts and visualizations.

Installation

npm install @hyperfrontend/random-generator-utils

Quick Start

import {
  randomGaussian,
  randomExponential,
  randomPowerLaw,
  randomUniform,
  randomPseudo,
  uuidV4,
  isUuidV4,
} from '@hyperfrontend/random-generator-utils'

// Gaussian (normal) distribution - ideal for modeling natural variation
const responseTime = randomGaussian(100, 300) // ms, centered around 200ms
const userHeight = randomGaussian(160, 180) // cm, most values near 170cm

// Exponential distribution - models time between independent events
const timeBetweenRequests = randomExponential(0.5) // λ=0.5, mean=2 seconds
const failureRate = randomExponential(0.1) // λ=0.1, mean=10 units

// Power law distribution - models "rich get richer" phenomena
const popularity = randomPowerLaw(2, 1, 1000) // Few items very popular
const citySize = randomPowerLaw(2.5, 100, 1000000) // Zipf's law for cities

// Uniform distribution - flat probability across range
const randomDelay = randomUniform(0, 1000) // Any value 0-1000ms equally likely

// Seeded pseudo-random for reproducible tests
const seed = 42
const value1 = randomPseudo(seed) // Always same output for seed=42
const value2 = randomPseudo(seed) // Identical to value1

// UUID generation
const id = uuidV4() // "a3bb189e-8bf9-4558-9e3e-e7b9a9e7b8c1"
console.log(isUuidV4(id)) // true
console.log(isUuidV4('not-a-uuid')) // false

API Overview

Statistical Distributions

  • randomUniform(min, max) - Uniform distribution (flat probability)
  • randomGaussian(min, max) - Gaussian/normal distribution (bell curve)
  • randomExponential(lambda) - Exponential distribution (decay)
  • randomPowerLaw(alpha, min, max) - Power law distribution (long tail)
  • randomLogarithmic(scale) - Logarithmic distribution

Pseudo-Random Generators

  • randomPseudo(seed) - Seeded pseudo-random (reproducible)
  • randomPseudoTimeBased(seedTime) - Time-based seeding for date/time variations

UUID Utilities

  • uuidV4() - Generate RFC 4122 version 4 UUID
  • isUuidV4(str) - Validate UUID v4 format

Use Cases

Load Testing

// Model realistic user behavior with varying response times
const users = Array.from({ length: 1000 }, () => ({
  thinkTime: randomExponential(0.5), // Time between actions
  responseTime: randomGaussian(50, 200), // Server response latency
  requestCount: Math.floor(randomPowerLaw(2, 1, 100)), // Request frequency
}))

Test Data Generation

// Generate reproducible test datasets
const seed = Date.now()
const testData = Array.from({ length: 50 }, (_, i) => ({
  id: uuidV4(),
  score: randomPseudo(seed + i) * 100, // Reproducible but varied
  timestamp: new Date(Date.now() + randomUniform(0, 86400000)),
}))

Procedural Content

// Generate varied but natural-looking values
const terrain = {
  height: randomGaussian(0, 100), // Centered around 50
  vegetation: randomUniform(0, 1), // Uniform coverage
  populationDensity: randomPowerLaw(2, 1, 1000), // Power law distribution
}

Compatibility

Platform Support
Browser
Node.js
Web Workers
Deno, Bun, Cloudflare Workers

Output Formats

Format File Tree-Shakeable
ESM index.esm.js
CJS index.cjs.js
IIFE bundle/index.iife.min.js
UMD bundle/index.umd.min.js

CDN Usage

<!-- unpkg -->
<script src="https://unpkg.com/@hyperfrontend/random-generator-utils"></script>

<!-- jsDelivr -->
<script src="https://cdn.jsdelivr.net/npm/@hyperfrontend/random-generator-utils"></script>

<script>
  const { randomGaussian, randomUniform, uuid4 } = HyperfrontendRandomGenerator
</script>

Global variable: HyperfrontendRandomGenerator

Part of hyperfrontend

This library is part of the hyperfrontend monorepo.

📖 Full documentation

License

MIT

API Reference§

Filter:

ƒFunctions

§function

isUuidV4(str: string): boolean

Validate if a string is a version 4 UUID.

Parameters

NameTypeDescription
§str
string
the string to be validated.

Returns

boolean
true if the string is a version 4 UUID, otherwise false.

Example

Validating user input as UUID

isUuidV4('a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d')
// => true

isUuidV4('not-a-uuid')
// => false

// Version 1 UUID (has '1' in third segment, not '4')
isUuidV4('550e8400-e29b-11d4-a716-446655440000')
// => false
§function

randomExponential(lambda: number): number

Generates a random number following an exponential distribution.

Parameters

NameTypeDescription
§lambda
number
The rate parameter (λ) controlling the distribution shape

Returns

number
A random number from the exponential distribution

Example

Modeling time between events (e.g., customer arrivals)

// Higher lambda = shorter average wait time
const averageWaitMinutes = 5
const lambda = 1 / averageWaitMinutes
const waitTime = randomExponential(lambda)
// => 3.7 (varies each call, most values clustered near 0-10)
§function

randomGaussian(min: number, max: number): number

Generates a random number following a Gaussian (normal) distribution within a specified range.

Parameters

NameTypeDescription
§min
number
The minimum value of the range
§max
number
The maximum value of the range

Returns

number
A random number from the Gaussian distribution bounded by min and max

Examples

Simulating human heights in centimeters

const heightCm = randomGaussian(150, 200)
// => 174.3 (most values cluster around the midpoint 175)

Generating test scores with realistic distribution

const testScore = randomGaussian(0, 100)
// => 52.8 (bell curve centered at 50, rarely hits extremes)
§function

randomLogarithmic(scale: number): number

Generates a random number following a logarithmic distribution.

Parameters

NameTypeDescription
§scale
number
The scale parameter controlling the distribution spread

Returns

number
A random number from the logarithmic distribution

Example

Generating values with exponential growth characteristics

// scale=1 produces values from 1 to e (~2.718)
const smallScale = randomLogarithmic(1)
// => 1.8 (values between 1 and ~2.7)

// scale=5 produces values from 1 to e^5 (~148)
const largeScale = randomLogarithmic(5)
// => 42.3 (wider range, skewed toward lower values)
§function

randomPowerLaw(alpha: number, min: number, max: number): number

Generates a random number following a power law distribution within a specified range.

Parameters

NameTypeDescription
§alpha
number
The power law exponent controlling the distribution
§min
number
The minimum value of the range
§max
number
The maximum value of the range

Returns

number
A random number from the power law distribution bounded by min and max

Examples

Simulating social network follower counts (few have many, many have few)

// alpha > 2 creates "long tail" - most values near min
const followerCount = randomPowerLaw(2.5, 1, 1000000)
// => 127 (typically low, occasionally very large)

Modeling file sizes in a system

const fileSizeKb = randomPowerLaw(2.0, 1, 10000)
// => 45 (many small files, rare large files)
§function

randomPseudo(seed: number): number

A simple pseudo-random number generator.

Parameters

NameTypeDescription
§seed
number
The seed for the generator.

Returns

number
A pseudo-random number between 0 and 1.

Example

Reproducible random values for testing

// Same seed always yields the same result
randomPseudo(42)
// => 0.6853... (deterministic)

randomPseudo(42)
// => 0.6853... (identical)

randomPseudo(43)
// => 0.1762... (different seed, different result)
§function

randomPseudoTimeBased(seedTime: Date): number

Generates a deterministic pseudo-random variation based solely on the seed time.

Parameters

NameTypeDescription
§seedTime
Date
The seed time for the variation.

Returns

number
The pseudo-random variation as a number.

Example

Reproducible randomness for a specific timestamp

const releaseDate = new Date('2024-03-15T10:30:00Z')

// Same date always produces the same result
const value1 = randomPseudoTimeBased(releaseDate)
const value2 = randomPseudoTimeBased(releaseDate)
// value1 === value2 (deterministic)
§function

randomUniform(min: number, max: number): number

Generates a random number uniformly distributed within a specified range.

Parameters

NameTypeDescription
§min
number
The minimum value of the range (inclusive)
§max
number
The maximum value of the range (exclusive)

Returns

number
A random number between min (inclusive) and max (exclusive)

Examples

Generating a random price within a budget range

const priceUsd = randomUniform(10, 50)
// => 27.34 (any value equally likely within range)

Random coordinates for game object placement

const xPosition = randomUniform(0, 800)
const yPosition = randomUniform(0, 600)
// => x: 342.7, y: 198.2
§function

uuidV4(): string

Generates a version 4 UUID.

Returns

string
a version 4 UUID.

Example

Creating unique identifiers for entities

const userId = uuidV4()
// => 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'

const sessionId = uuidV4()
// => '9f8e7d6c-5b4a-4321-8765-4321fedcba98'

Related