⚠️ Breaking Changes in Version 2.0.0
Version 2.0.0 ofjs-randomize
introduces breaking changes. Please refer to the CHANGELOG for details on what has changed and how to adapt your code.
js-randomize
is a lightweight TypeScript library that provides utility functions for generating random integers, floats, booleans, arrays, and strings. It supports custom random number generators and is perfect for applications like games, testing, or simulations.
To install using pnpm
:
pnpm add js-randomize
Or, using npm
:
npm install js-randomize
Since the package is now ESM-only, use the import
syntax to include it in your project:
import { Randomize } from 'js-randomize';
const randomize = new Randomize(); // Use the default Math.random() or pass a custom random generator
const randomInt = randomize.integer(1, 10);
// randomInt is an integer between 1 and 10 (inclusive)
const randomFloat = randomize.float(0, 1, 3);
// randomFloat is a float between 0 and 1 with 3 decimal places
const randomIntArray = randomize.intArray(5, 1, 100);
// randomIntArray is an array of 5 random integers between 1 and 100
const randomFloatArray = randomize.floatArray(5, 0, 1, 2);
// randomFloatArray is an array of 5 random floats between 0 and 1 with 2 decimal places
const randomBool = randomize.boolean();
// randomBool is either true or false
const array = ['apple', 'banana', 'cherry'];
const randomElement = randomize.pick(array);
// randomElement is a random item from the array
const randomSample = randomize.sample(array, 2);
// randomSample contains 2 random non-repeating items from the array
const shuffledArray = randomize.shuffle(array);
// shuffledArray is a shuffled version of the original array
const randomString = randomize.string(8);
// randomString is a random 8-character string (alphanumeric by default)
You can also provide a custom random generator function:
const customRandomFn = () => 0.5;
const customRandomize = new Randomize(customRandomFn);
const randomInt = customRandomize.integer(1, 10);
// With the custom random function, the result will always be 5
import { Randomize } from 'js-randomize';
const randomize = new Randomize();
const randomInt: number = randomize.integer(1, 10);
Pull requests are welcome! For major changes, please open an issue first to discuss what you'd like to change. Make sure to update tests as appropriate.