Skip to content

Instantly share code, notes, and snippets.

@maxktz
Last active May 17, 2025 15:54
Show Gist options
  • Save maxktz/991a31f9c894cde4d18a93a0e18d4e52 to your computer and use it in GitHub Desktop.
Save maxktz/991a31f9c894cde4d18a93a0e18d4e52 to your computer and use it in GitHub Desktop.
RangedNumber, utility class used to store range of numbers and get random, or mid value easily
/**
* @example
* // Example usage:
* let rn = RangedNumber.fromString("1");
* console.log(rn); // RangedNumber { min: 1, mid: 1, max: 1 }
*
* let rn = RangedNumber.fromString("1-2");
* console.log(rn); // RangedNumber { min: 1, mid: 1.5, max: 2 }
*
* let randomNumber = rn.get();
* console.log(randomNumber); // 1.94
* console.log(rn.get()); // 1.55
* console.log(rn.get()); // 1.98
* console.log(rn.get()); // 1.7
*
* */
export class RangedNumber {
min: number;
max: number;
mid: number;
fix: number;
constructor(min: number, max?: number, digitsAfterComma = 2) {
max = max !== undefined ? max : min;
RangedNumber.validate(min, max);
this.min = min;
this.mid = (min + max) / 2;
this.max = max;
this.fix = 10 ** digitsAfterComma;
}
static validate(min: number, max: number) {
if (isNaN(min) || isNaN(max) || min > max) {
throw new Error("RangedNumber invalid input data");
}
}
static fromString(str: string): RangedNumber {
let [min, max] = str.split("-").map(Number);
max = max !== undefined ? max : min;
RangedNumber.validate(min, max);
return new RangedNumber(min, max);
}
get(): number {
const num = Math.random() * (this.max - this.min) + this.min;
return Math.round(num * this.fix) / this.fix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment