Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
random-elements
Advanced tools
Provides a nicely-typed, well-tested utility for picking one or multiple random element(s) from an array.
Pretty simple.
The main benefits of this over doing it yourself:
pickRandomIndex
pickRandomIndexes
pickRandomElement
(type safe arrays! no mutation!)pickMultipleRandomElements
(same as above, but returns multiple elements)const myArray = ["one", "two", "three"];
const answer = pickRandomElement(myArray);
// Typescript will know that "answer" is a string
Sometimes you want to weight certain outcomes more or less likely than others. This library lets you pass a Map of keys with relative probabilities (weights), and each time you call the function, you will get a single key back but with the probabilities stacked in favour of the ones you weighted higher.
pickKeysWithWeights
Note the different ways of building the Map object; either construct an empty one and set
some elements (Example 1), or do it in one go, in the constructor (Example 2).
const weights = new Map();
weights.set("one", 1);
weights.set("two", 1);
weights.set("three", 2);
const pick = pickKeysWithWeights(weights);
// Expect to get "three" roughly twice as often compared to "one" or "two". The chances of getting "three" any given time is 50%, however - that's probability, folks!
const weights = new Map([
["heads", 2],
["tails", 1]
]);
const pick = pickKeysWithWeights(weights);
// Expect to get "heads" roughly twice as often as "tails". That means 66.6% chance vs 33.3% chance, right?
FAQs
Utility for picking one or more elements from any array
The npm package random-elements receives a total of 2 weekly downloads. As such, random-elements popularity was classified as not popular.
We found that random-elements demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.