py-random-js
v2.0.0
Published
Python-style 'random' library for JavaScript
Downloads
170
Readme
Randomizer.js
Stop wrestling with Math.floor(Math.random() * ...)!
Are you coming from Python and missing the simplicity of the random module? Or are you just tired of writing the same boilerplate code every time you need a random integer or a shuffled array?
Randomizer.js is a lightweight, zero-dependency utility that brings Python-style randomness to the JavaScript world.
Features
- Python-like API: Simple, clean, and intuitive methods.
- Game-Dev Ready: Includes shuffling, coin flips, and percentage chances.
- Modern JS: Written as an ES Module for maximum compatibility.
- Lightweight: Only what you need, nothing you don't.
Installation
npm install py-random-jsUsage
import random from 'py-random-js';
// 1. Get a random integer between 0 and 50 (inclusive)
console.log(random.int(50));
// 2. Pick a random element from an array
const items = ['Sword', 'Shield', 'Potion', 'Spell'];
console.log(random.array(items));
// 3. Shuffle an array (Fisher-Yates algorithm)
const deck = [1, 2, 3, 4, 5];
console.log(random.shuffle(deck));
// 4. Flip a coin (50/50 chance)
if (random.coinFlip()) {
console.log("Heads!");
} else {
console.log("Tails!");
}
// 5. Roll for a specific chance (e.g., 15% for a Critical Hit)
if (random.chance(15)) {
console.log("CRITICAL HIT!");
}
// Generate a string of a certain length containing random characters (e.g., generate an ID)
console.log(`Random generated string: ${random.string(16)}`) // Random generated string: gfCFSYMsB4ygLEsWAPI Reference
| Method | Arguments | Description | | :---: | :---: | :---: | | .int(max) | number | Returns a random integer from 0 to max (inclusive). | | .array(array) | Array | Returns one random element from the provided array. | | .shuffle(array) | Array | Returns a NEW shuffled version of the array. | | .coinFlip() | none | Returns true or false with a 50% probability. | | .chance(n) | number | Returns true with a n percent probability (0-100). | | .string(n) | number | Returns a string of length n containing random characters. |
Author: bodutop License: MIT
