Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: datatype.number when min = max + precision, throw when max > min #664

Merged
merged 15 commits into from
Mar 31, 2022
30 changes: 9 additions & 21 deletions src/datatype.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,39 +41,27 @@ export class Datatype {
number(
options?: number | { min?: number; max?: number; precision?: number }
): number {
if (typeof options === 'number') {
options = { max: options };
}

options = options ?? {};
const opts = typeof options === 'number' ? { max: options } : options ?? {};

let max = 99999;
let min = 0;
let precision = 1;
if (typeof options.min === 'number') {
min = options.min;
}

if (typeof options.max === 'number') {
max = options.max;
}
const precision = typeof opts.precision === 'number' ? opts.precision : 1;
const min = typeof opts.min === 'number' ? opts.min : 0;
let max = typeof opts.max === 'number' ? opts.max : min + 99999;
pkuczynski marked this conversation as resolved.
Show resolved Hide resolved
pkuczynski marked this conversation as resolved.
Show resolved Hide resolved

if (typeof options.precision === 'number') {
precision = options.precision;
if (max <= min) {
throw new Error(`Max should be larger then min: ${max} > ${min}`);
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
}
pkuczynski marked this conversation as resolved.
Show resolved Hide resolved

// Make the range inclusive of the max value
if (max >= 0) {
max += precision;
}

let randomNumber = Math.floor(
const randomNumber = Math.floor(
this.faker.mersenne.rand(max / precision, min / precision)
);
// Workaround problem in Float point arithmetics for e.g. 6681493 / 0.01
randomNumber = randomNumber / (1 / precision);

return randomNumber;
// Workaround problem in float point arithmetics for e.g. 6681493 / 0.01
return randomNumber / (1 / precision);
}

/**
Expand Down
8 changes: 6 additions & 2 deletions src/random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,12 @@ export class Random {
arrayElement<T = string>(
array: ReadonlyArray<T> = ['a', 'b', 'c'] as unknown as ReadonlyArray<T>
): T {
const r = this.faker.datatype.number({ max: array.length - 1 });
return array[r];
const index =
array.length > 1
? this.faker.datatype.number({ max: array.length - 1 })
: 0;
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved

return array[index];
}

/**
Expand Down