aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLeyla Jähnig <[email protected]>2022-03-21 14:19:36 +0100
committerGitHub <[email protected]>2022-03-21 13:19:36 +0000
commit9ab0825add89474635bcc3b60595abd584088138 (patch)
tree1143b246137d93a35b357e320cd8e3d89bbf5d1a
parent486c76e34f22cf1fd66fa2c99e605d52c7077760 (diff)
downloadfaker-9ab0825add89474635bcc3b60595abd584088138.tar.xz
faker-9ab0825add89474635bcc3b60595abd584088138.zip
refactor: make number input immutable (#545)
Co-authored-by: Leyla Jähnig <[email protected]>
-rw-r--r--src/datatype.ts25
-rw-r--r--test/datatype.spec.ts27
2 files changed, 30 insertions, 22 deletions
diff --git a/src/datatype.ts b/src/datatype.ts
index ba2ebdc4..706ed60e 100644
--- a/src/datatype.ts
+++ b/src/datatype.ts
@@ -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;
}
diff --git a/test/datatype.spec.ts b/test/datatype.spec.ts
index bee280d7..35ac512f 100644
--- a/test/datatype.spec.ts
+++ b/test/datatype.spec.ts
@@ -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';
+ 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);
});
});