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

refactor: make number input immutable #545

Merged
merged 2 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions src/datatype.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,32 +47,31 @@ export class Datatype {

options = options ?? {};

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

if (typeof options.max === 'undefined') {
options.max = 99999;
if (typeof options.max === 'number') {
max = options.max;
}

if (typeof options.precision === 'undefined') {
options.precision = 1;
if (typeof options.precision === 'number') {
precision = options.precision;
}

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

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

return randomNumber;
}
Expand Down
27 changes: 18 additions & 9 deletions test/datatype.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,18 +445,27 @@ describe('datatype', () => {
}
});

it('should not modify the input object', () => {
const min = 1;
const max = 2;
const opts = {
min: min,
max: max,
it('should not mutate the input object', () => {
const initalMin = 1;
const initalPrecision = 1;
const initalOtherProperty = 'hello darkness my old friend';
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
const input: {
min?: number;
max?: number;
precision?: number;
otherProperty: string;
} = {
min: initalMin,
precision: initalPrecision,
otherProperty: initalOtherProperty,
};

faker.datatype.number(opts);
faker.datatype.number(input);

expect(opts.min).toBe(min);
expect(opts.max).toBe(max);
expect(input.min).toBe(initalMin);
expect(input.precision).toBe(initalPrecision);
expect(input.max).toBe(undefined);
expect(input.otherProperty).toBe(initalOtherProperty);
});
});

Expand Down