bitburner-src/utils/helpers/addOffset.ts

24 lines
750 B
TypeScript
Raw Normal View History

/**
* Adds a random offset to a number within a certain percentage
* @example
* // Returns between 95-105
* addOffset(100, 5);
* @example
* // Returns between 63-77
* addOffSet(70, 10);
* @param midpoint The number to be the midpoint of the offset range
* @param percentage The percentage (in a range of 0-100) to offset
*/
2021-05-01 09:17:31 +02:00
export function addOffset(midpoint: number, percentage: number): number {
2021-09-05 01:09:30 +02:00
const maxPercent = 100;
if (percentage < 0 || percentage > maxPercent) {
return midpoint;
}
2021-09-05 01:09:30 +02:00
const offset: number = midpoint * (percentage / maxPercent);
2021-09-05 01:09:30 +02:00
// Double the range to account for both sides of the midpoint.
// tslint:disable-next-line:no-magic-numbers
return midpoint + (Math.random() * (offset * 2) - offset);
}