Boolean Probability Distribution Using Lodash random
This article explains how to leverage the Lodash
_.random method to generate boolean values based on custom
probability distributions. While _.random natively
generates numerical values, enabling its floating-point functionality
allows you to model weighted true and false outcomes with precise
statistical control.
Basic 50/50 Boolean Generation
By default, calling _.random(0, 1) yields an integer of
either 0 or 1, each with an equal 50% chance.
You can cast this result directly to a boolean:
const isTrue = Boolean(_.random(0, 1));Implementing Weighted Probability Distributions
To create an uneven probability distribution (for example, an 80%
chance of returning true and a 20% chance of returning
false), configure _.random to return a
floating-point number between 0 and 1.
The syntax for _.random is
_.random([lower=0], [upper=1], [floating]). Setting the
third argument to true produces a continuous floating-point
value.
// Function that returns true based on a specified probability (between 0 and 1)
function getRandomBoolean(probability = 0.5) {
return _.random(0, 1, true) < probability;
}
// 70% chance of true, 30% chance of false
const eventOccurred = getRandomBoolean(0.7);
// 15% chance of true, 85% chance of false
const rareEvent = getRandomBoolean(0.15);Integer-Based Percentage Approach
If you prefer working directly with percentages rather than decimals,
configure the range between 1 and 100 using
standard integer outputs:
function getPercentChance(percentage) {
return _.random(1, 100) <= percentage;
}
// 25% chance of returning true
const isQuarterChance = getPercentChance(25);Using floating-point numbers between 0 and
1 is optimal for standard mathematical probabilities, while
the integer method from 1 to 100 provides an
intuitive syntax for percentage-based logic.