JavaScripteasyJavaScript

Random Data Generator

Generates random numbers within ranges or random strings

01

The problem

Need to generate random data for testing or demonstrations

02

The solution

JavaScript
const random = {
  // Generate random integer within range
  int(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  
  // Generate random string
  string(length = 8, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
    let result = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  },
  
  // Generate random color
  color() {
    return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
  },
  
  // Randomly select element from array
  choice(array) {
    return array[Math.floor(Math.random() * array.length)];
  },
  
  // Generate random boolean
  bool() {
    return Math.random() >= 0.5;
  }
};

03

Put it to work

Example
console.log(random.int(1, 100)); // Random integer 1-100
console.log(random.string(10)); // 10-character random string
console.log(random.color()); // Random hex color
console.log(random.choice(['apple', 'banana', 'orange'])); // Random fruit
console.log(random.bool()); // Random true/false