From 8e459e83377e2196653c6d5b553ee9e692d50732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leyla=20J=C3=A4hnig?= Date: Tue, 22 Feb 2022 22:18:19 +0100 Subject: [PATCH 1/2] refactor: remove input mutability for datatype.number --- src/datatype.ts | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/datatype.ts b/src/datatype.ts index ba2ebdc4685..706ed60e906 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; } From 7b7614a51d7cc9e7c28b2e02fe6dee15242b4732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leyla=20J=C3=A4hnig?= Date: Tue, 22 Feb 2022 22:26:01 +0100 Subject: [PATCH 2/2] test: case for dataype.number input mutation --- test/datatype.spec.ts | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/test/datatype.spec.ts b/test/datatype.spec.ts index bee280d7bf1..35ac512fd06 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); }); });