This repository has been archived on 2025-07-16. You can view files and clone it, but cannot push or open issues or pull requests.
Files
vue-with-websockets/backend/utils/random.js
2025-07-07 15:52:32 +03:00

34 lines
1.1 KiB
JavaScript

/**
* Generates a random integer between min and max (inclusive)
* @param {number} min
* @param {number} max
* @returns {number}
*/
export function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Generates a random number based on previous number, and provided range
* Also taking into account global provided min and max values
* @param {number} previousNumber
* @param {number} range (0 - 1)
* @param {number} min
* @param {number} max
* @returns {number}
*/
export function randomInRange(previousNumber, range, min, max) {
// Decides on min max range for the next number
// based on range, and previous number
const integerRange = previousNumber * range; // +- 0.3 -> 30%
// Calculate min, and check if its less that global min (eg. 0)
let newMin = previousNumber - integerRange;
if (newMin < min) newMin = min; // sets to global min, for example 0
// calculate max, and check if number is above the global set max (eg. 100)
let newMax = previousNumber + integerRange;
if (newMax > max) newMax = max; // sets to global max, for example 100
return Math.floor(randomInt(newMin, newMax));
}