npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

random-seed-weighted-chooser

v1.1.10

Published

A random weighted item chooser with custom seed option for JavaScript and TypeScript.

Downloads

5,179

Readme

Documentation

Read the official documentation.

Overview

A random weighted item chooser with custom seed option for JavaScript.

This package allows you to choose an index from an array of weights (simplest case), or an object from an array of objects that each have a customizable "weight" property.

It also allows you to specify default weights, and to use your own seed for the pseudorandom number generator (PRNG).

Features include:

  • 🎲 Choose weighted items at random
    • Randomly select items based on weights
  • 💪 Flexible and customizable
    • Choose an index from an array of weights, or an object from an array of objects with weight properties
  • 🌱 Custom seed support
    • Provide your own seed for full control of the PRNG results

Donate

If this project helped you, please consider buying me a coffee or sponsoring me. Your support is much appreciated!

 

Table of Contents

Installation

npm i random-seed-weighted-chooser

Quick Start

Two ways:

  • Randomly choose an index from an array of weights.
  • Randomly choose an object from an array of objects with weight properties.

Using An Array Of Weights

You can use an array of weight numbers to randomly choose an index in that array.


// ...
// Returns an index using the weights to determine chance, or -1 if empty.
Chooser.chooseWeightedIndex(arrayOfWeights);
// Optionally, you can use a custom seed. Math.random() is used as the default.
Chooser.chooseWeightedIndex(arrayOfWeights, seed);
// You can also specify a default weight to use if your array contains 
// non-numbers (this is a failsafe).
Chooser.chooseWeightedIndex(arrayOfWeights, seed, defaultWeight);

If all weights are 0, -1 is returned.

Using An Array Of Objects With Weight Properties

You can use an array of objects, each with a weight property and number value, to randomly choose one of those objects.

import Chooser from "random-seed-weighted-chooser";

// ...
// Expects each object to have a "weight" property. Returns null if array is empty.
Chooser.chooseWeightedObject(arrayOfObjects);
// Uses custom property key, default weight (if weight property is missing), and custom seed.
Chooser.chooseWeightedObject(
  arrayOfObjects,
  weightPropertyKey,
  defaultWeight,
  seed
);

If all weights are 0, null is returned.

Bad Input

For any non-object where an object is expected, or non-number weight where a number is expected:

  • That item will have the default weight. This will be 1 or the optional default value if provided.

All negative weights are treated as positive.

Examples

Weighted Random Index Choice Example

If all you need is an index, you can just use a number[] array of weights, like so:

import Chooser from "random-seed-weighted-chooser";

let arrayOfWeights = [10, 50, 35, 5];

// Returns the randomly chosen index or -1 if the array is empty. 
// Uses Math.random() as the seed.
Chooser.chooseWeightedIndex(arrayOfWeights);
// 10% chance of returning 0
// 50% chance of returning 1
// 35% chance of returning 2
// 5% chance of returning 3

Under the hood, this project uses a pseudorandom number generator (PRNG) that allows the developer to provide their own seed.

So if you want to provide your own seed, you can. Seeds can be any value (strings, numbers, etc):

// Returns the randomly chosen index or -1 if the array is empty.
// Will return the same result until the seed changes.
let seed = "myseed";
Chooser.chooseWeightedIndex(arrayOfWeights, seed); // 3
Chooser.chooseWeightedIndex(arrayOfWeights, seed); // 3
Chooser.chooseWeightedIndex(arrayOfWeights, seed); // Always 3
seed = 12345;
Chooser.chooseWeightedIndex(arrayOfWeights, seed); // 1
Chooser.chooseWeightedIndex(arrayOfWeights, seed); // 1
Chooser.chooseWeightedIndex(arrayOfWeights, seed); // Always 1

Weighted Random Item Choice Example

let iceCreamFlavors = [
  { flavor: "chocolate", weight: 3 },
  { flavor: "vanilla", weight: 1 },
  { flavor: "piña colada", weight: 6 }
];

// Returns the randomly chosen object based on their weights.
// - Looks for a property called "weight"; default 1 if not found
// - Uses Math.random() as the seed.
Chooser.chooseWeightedObject(iceCreamFlavors);
// chocolate = 30% chance
// vanilla = 10% chance
// piña colada = 60% chance

You can use any number property as the weight. Just provide the property key as the second argument, like so:

let restaurantRatings = [
  { name: "Chipotle", rating: 4.2 },
  { name: "Moe's", rating: 4.9 },
  { name: "Dirty Bill's", rating: 1.2 }
];

// This example uses restaurant ratings as weights.
Chooser.chooseWeightedObject(restaurantRatings, "rating");
// Chipotle = 40.8% chance
// Moe's = 47.6% chance
// Dirty Bill's = 11.7% chance

If the property is not found, the default weight is 1. You can provide a default if you'd like. The seed defaults to Math.random(), but you can provide your own seed if you'd like as well:

let restaurantRatings = [
  { name: "Chipotle", rating: 4.2 },
  { name: "Moe's", rating: 4.9 },
  { name: "Edgy Burrito" } // Unrated restaurant
];

// Uses "rating" as weight, a default weight of 2.5, and a custom seed.
let seed = "Brianna's pick";
Chooser.chooseWeightedObject(restaurantRatings, "rating", 2.5, seed);
// Chipotle = 36.2% chance
// Moe's = 42.2% chance
// Edgy Burrito = 21.6% chance (no rating property, so uses 2.5 default)

Lottery Example

Below we have a lottery with 100000 items in the bag (weights total 100000).

let lottery = [
  { name: "Impossible", weight: 0 },
  { name: "Nearly impossible", weight: 1 },
  { name: "Very low chance", weight: 9 },
  { name: "Low chance", weight: 90 },
  { name: "Medium chance", weight: 900 },
  { name: "High chance", weight: 9000 },
  { name: "Very high chance", weight: 90000 }
];

Chooser.chooseWeightedObject(lottery);
// "Nearly impossible" has 1/100000 odds of occurring.

🎉 Happy Random Seed Weighted Choosing! 🎉

TypeScript

Type definitions have been included for TypeScript support.

Icon Attribution

Favicon by Twemoji.

Contributing

Open source software is awesome and so are you. 😎

Feel free to submit a pull request for bugs or additions, and make sure to update tests as appropriate. If you find a mistake in the docs, send a PR! Even the smallest changes help.

For major changes, open an issue first to discuss what you'd like to change.

⭐ Found It Helpful? Star It!

If you found this project helpful, let the community know by giving it a star: 👉⭐

License

See LICENSE.md.