3.12.112 • Published 11 months ago

@devtea2026/excepturi-nemo-reiciendis-soluta v3.12.112

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

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 @devtea2026/excepturi-nemo-reiciendis-soluta

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 "@devtea2026/excepturi-nemo-reiciendis-soluta";

// ...
// 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 "@devtea2026/excepturi-nemo-reiciendis-soluta";

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.

storagegatewayfile systemgradients cssphonecollection0concatconsolereact-hook-formimportexportsetelectroninternalgetPrototypeOfflagsecmascriptfromreal-timeviewcallmatchAllexpressgetOwnPropertyDescriptorchromefast-copysearchbreaklivefpsvariables in csslastflatMapcallbindPromisepicomatchfindupcacheObservablemulti-packageeslintplugincss nestingobjinstallertslibWebSocketvestconnectcommanderrobustArray.prototype.flatMapnameschromiumduplexwaitinECMAScript 2017awesomesauceajvprocessECMAScript 5endpointdynamodbescapeargparsebootstrap cssstylesdescription$.extendjsonpathcss-in-jsfigletcall-bindObject.fromEntriesextensionclassnameRxtrimtsES2022assignregular expressiondotenvchaiiterateRxJSjsdiffcode pointsredactformattingArray.prototype.findLastIndexArray.prototype.filterthrottleUint8ClampedArrayfasttoSortedmkdirphashtoArraysymlinkfindStyleSheetobjects3trimEndinferencegdprtypedarrayarraybufferES2019clifsindicatorfseventscssawaiterror-handlingvisuallistenersbluebirdhas-ownexpressionimmerTypeScriptStreampersistent[[Prototype]]Object.getPrototypeOfpushArrayBuffer#sliceio-tsformstouchyupcallboundrdschannelmomentmake dirsettingslinuxstableObject.keysprefixdomnegative zeroes-shimschineseES2017cloneprotobufwhichqueryfast-clonenativeObjectsigintbufferjapanesereducerES2015formatoncefixed-widthrm -rfstatusbrowserlistparseschemeextendvalueexitlesspropertiesmime-dbhttpsa11yFloat32Arrayassertsprotoidlebdddeepclonedeletedeep-copybundlerparentsaccessorpostcss@@toStringTages2015sharedstylesheetloggereventEmitter256cloudformationfilterttyvarsjoimixinsECMAScript 2018consumebindpackagecorsstateECMAScript 2015weakmapstyled-componentsglobeslinttapeclassnamesdefinePropertycompilerUint16Arraygenericsless compilerpositivegroupBywordbreakjwtshrinkwrapcomparebcryptapollorestruntimees2016ec2routeriamkinesistrimStarttrimLeftFunction.prototype.nameconfigstructuredClonerangeerrorarktypejsxyamlcurldataviewclientinspectansipackage managercolumnsqueueMicrotaskvalidless csstoolkitinterruptsgetoptnumberassertpackage.jsonsequencedeterministicwidthdirfind-upfunctiones-abstractstreamscodessymlinksmetadatarecursivejavascriptdeep-clonespeedemojiArray.prototype.includesless mixinsgetwhatwgbuffersbannerES2021globales5cryptcircularidentifiersfilees8react-hooksinputelasticachestyleflagwordwrapimmutableconfigurablepredictable_.extendlintownschemaECMAScript 2023ECMAScript 6ES3resolveequalitypromisekoreanlook-uptoobjectmimetc39call-boundflatStreamseslint-pluginshamoperating-systemRegExp.prototype.flagsbootstrap lessremovelibphonenumbershebanghookspackagescomputed-typesimportArray.prototype.containsdebugclassesstylingcontainsfullHyBisyntaxerrordom-testing-libraryESnextcompile lessiterationemitrandomECMAScript 2021toStringTagpolyfillsameValueZeroSymbolpluginrequirelesscsshttpwatchFilevaluesqsmatchBigInt64ArrayoptimizerObservablesfindLastIndexArray.prototype.findLastdataViewoptimistes2018invariantroute53authenticationBigUint64Arraykeyrfc4122linewrappatchglobalstakedeepcopysqsutilitytimetextarraysbyteJSONfunctionalproxydateglaciercopyprivate dataenvironmentstatelessgetteridmochastyleguideentrieslanguagextermUnderscoreES2020trimRightfetchsharedarraybufferscheme-validationquoteforEachlrulockfilemkdirssnssymbols-0validationregularfunctionsTypeBoxautoscalingiteratorefficientxhrairbnbRegExp#flagscloudfrontistestersyntaxECMAScript 3replayregexpJSON-Schemaloadingform-validationwalksignalslogmodulesunicodeprettyes2017setterhotloadbalancingemrstringReactiveXlimitserializerpipeoffsetzodeventshasdefinesuperstructObject.definePropertyfullwidthcloudwatchapielmAsyncIteratortostringtagtddutilspeccensorastreadablestreamqueuejshintArrayBuffergraphqlWeakMapdebuggerstreams2es6flattenInt8Arraytasksinatradropjsdomes-shim APIjestmoveirqmonorepoFloat64ArraypruneES5avacoercibleomitbundlinglengthsomeparsingmergedependenciesrestfultypeofnodebusyratelimitcreateES6concurrencylooktestinghigher-ordersuperagentdependency managerbyteOffsetmacosdirectoryeventDispatchercss variablemapreducemruquerystringdatarmfastcloneserializationhandlerscloudsearchtypesreuseencryptionguidenvinstallgetintrinsicpasswordclass-validatoraccessibilityrgbenderfluxhardlinksopenfast-deep-cloneesconcatMaptypescripttypesafeSymbol.toStringTagzeroargvmiddlewarenpmbatchreduxES2016YAMLthroatworkergradients css3cloudtrailreact-testing-libraryUint32Arraycss lesssigtermrm -frwarninguuidPushcommand-linepreprocessorstringifywebbrowserslistES7hasOwnstringifierprogressObject.valuescjktapuninstallspinnererrornopewritepostcss-pluginarrayECMAScript 2019browsermimetypesassertionSetminimalArrayequalArray.prototype.flattenReactiveExtensionseslintconfigjsCSStest.envnegativereduceparserboundpyyamlES2018linkString.prototype.trimdescriptorwafextraexit-codepromisescolorObject.entriesvariableswraphasOwnPropertyexecnested csslazyagentpathES2023limitedMapWeakSetInt32ArrayserializeObject.assigncolourawsloggingjasminestreamMicrosoftReflect.getPrototypeOfsespropertyebsponyfillratetypedarraysl10nurl__proto__artintrinsicajaxbyteLengthgroupcolumninternal slotappURLArray.prototype.flatasyncECMAScript 7beanstalkwalkingrmdirperformantmobilejQueryshellWebSocketsCSSStyleDeclarationvpcargumentutilitieswatchervalidateenumerablecollection.es6readableESelbtyped arrayisConcatSpreadablefull-widthdeepfast-deep-copycharactersInt16ArraysafeperformanceworkflowRFC-6455Uint8ArrayES8fastcopydifftelephonekarmaworkspace:*ArrayBuffer.prototype.sliceincludesenvironmentssliceproptraversefastifynodejsauthspinnersdescriptorsutil.inspecthookformcoreasciitypeslotcryptoURLSearchParamsprototypesidemkdirECMAScript 2020es7typedsortnamesortedframeworksimpledbreactpreserve-symlinksObject.isieshimsymboleveryautoprefixerweaksetformmakeregular expressionsless.jscommandfindLast
3.12.112

11 months ago

3.12.111

11 months ago

3.12.110

11 months ago

3.11.110

11 months ago

3.10.110

11 months ago

3.10.109

11 months ago

3.10.108

11 months ago

3.10.107

11 months ago

1.4.20

1 year ago

1.4.22

1 year ago

1.4.21

1 year ago

1.4.24

1 year ago

1.4.23

1 year ago

1.4.26

1 year ago

1.4.25

1 year ago

1.4.28

1 year ago

1.4.27

1 year ago

1.4.29

1 year ago

3.9.107

11 months ago

2.9.96

11 months ago

2.9.97

11 months ago

2.9.95

11 months ago

3.9.102

11 months ago

3.9.105

11 months ago

3.9.106

11 months ago

3.9.103

11 months ago

3.9.104

11 months ago

1.8.78

12 months ago

1.4.31

1 year ago

1.8.79

12 months ago

1.4.30

1 year ago

1.6.59

1 year ago

2.9.98

11 months ago

2.9.99

11 months ago

1.7.70

1 year ago

1.7.71

1 year ago

1.7.72

1 year ago

2.9.100

11 months ago

1.7.73

1 year ago

1.5.50

1 year ago

2.9.101

11 months ago

1.7.74

1 year ago

2.9.102

11 months ago

1.7.75

1 year ago

1.5.52

1 year ago

1.7.76

1 year ago

1.5.51

1 year ago

1.7.77

1 year ago

1.5.54

1 year ago

1.7.78

12 months ago

1.5.53

1 year ago

1.5.56

1 year ago

1.5.55

1 year ago

1.5.58

1 year ago

1.5.57

1 year ago

1.5.59

1 year ago

1.4.19

1 year ago

1.4.18

1 year ago

1.5.32

1 year ago

1.5.31

1 year ago

1.5.34

1 year ago

1.5.33

1 year ago

1.5.36

1 year ago

1.5.35

1 year ago

1.5.38

1 year ago

1.5.37

1 year ago

1.5.39

1 year ago

1.5.41

1 year ago

1.5.40

1 year ago

1.5.43

1 year ago

1.5.42

1 year ago

1.7.68

1 year ago

1.5.45

1 year ago

1.7.69

1 year ago

1.5.44

1 year ago

2.8.89

12 months ago

1.5.47

1 year ago

2.8.88

12 months ago

1.5.46

1 year ago

1.5.49

1 year ago

1.5.48

1 year ago

2.8.92

12 months ago

2.8.91

12 months ago

2.8.90

12 months ago

2.8.95

12 months ago

2.8.94

12 months ago

2.8.93

12 months ago

1.8.80

12 months ago

1.8.81

12 months ago

1.8.82

12 months ago

1.8.83

12 months ago

1.6.60

1 year ago

1.8.84

12 months ago

1.8.85

12 months ago

1.6.62

1 year ago

1.8.86

12 months ago

1.6.61

1 year ago

1.8.87

12 months ago

1.6.64

1 year ago

1.8.88

12 months ago

1.6.63

1 year ago

1.6.66

1 year ago

1.6.65

1 year ago

1.6.68

1 year ago

1.6.67

1 year ago

1.4.17

1 year ago

1.4.16

1 year ago

1.4.13

1 year ago

1.4.15

1 year ago

1.4.14

1 year ago

1.4.12

1 year ago

1.3.12

1 year ago

1.2.12

1 year ago

1.2.11

1 year ago

1.2.10

1 year ago

1.1.10

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago