aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorShinigami <[email protected]>2022-05-23 08:59:02 +0200
committerGitHub <[email protected]>2022-05-23 06:59:02 +0000
commit1793385c1ea7b7db349720c7bab20ac9765e9200 (patch)
tree6dd914b0e7908b1c3a93a288ac252b7bf28f5312 /src
parent73db3a77d95a21e320888228e39ebbf60d551451 (diff)
downloadfaker-1793385c1ea7b7db349720c7bab20ac9765e9200.tar.xz
faker-1793385c1ea7b7db349720c7bab20ac9765e9200.zip
feat: reimplement datatype.bigInt (#791)
Co-authored-by: ST-DDT <[email protected]>
Diffstat (limited to 'src')
-rw-r--r--src/modules/datatype/index.ts59
1 files changed, 49 insertions, 10 deletions
diff --git a/src/modules/datatype/index.ts b/src/modules/datatype/index.ts
index df2cac87..c8b9718f 100644
--- a/src/modules/datatype/index.ts
+++ b/src/modules/datatype/index.ts
@@ -261,20 +261,59 @@ export class Datatype {
/**
* Returns a [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type) number.
*
- * @param value When provided, this method simply converts it to `BigInt` type.
+ * @param options Maximum value or options object.
+ * @param options.min Lower bound for generated bigint. Defaults to `0n`.
+ * @param options.max Upper bound for generated bigint. Defaults to `min + 999999999999999n`.
+ *
+ * @throws When options define `max < min`.
*
* @example
- * faker.datatype.bigInt() // 8507209999914928n
- * faker.datatype.bigInt('156') // 156n
- * faker.datatype.bigInt(30) // 30n
- * faker.datatype.bigInt(3000n) // 3000n
- * faker.datatype.bigInt(true) // 1n
+ * faker.datatype.bigInt() // 55422n
+ * faker.datatype.bigInt(100n) // 52n
+ * faker.datatype.bigInt({ min: 1000000n }) // 431433n
+ * faker.datatype.bigInt({ max: 100n }) // 42n
+ * faker.datatype.bigInt({ min: 10n, max: 100n }) // 36n
*/
- bigInt(value?: string | number | bigint | boolean): bigint {
- if (value === undefined) {
- value = Math.floor(this.number() * 99999999999) + 10000000000;
+ bigInt(
+ options?:
+ | bigint
+ | boolean
+ | number
+ | string
+ | {
+ min?: bigint | boolean | number | string;
+ max?: bigint | boolean | number | string;
+ }
+ ): bigint {
+ let min: bigint;
+ let max: bigint;
+
+ if (typeof options === 'object') {
+ min = BigInt(options.min ?? 0);
+ max = BigInt(options.max ?? min + BigInt(999999999999999));
+ } else {
+ min = BigInt(0);
+ max = BigInt(options ?? 999999999999999);
}
- return BigInt(value);
+ if (max === min) {
+ return min;
+ }
+
+ if (max < min) {
+ throw new FakerError(`Max ${max} should be larger then min ${min}.`);
+ }
+
+ const delta = max - min;
+
+ const offset =
+ BigInt(
+ this.faker.random.numeric(delta.toString(10).length, {
+ allowLeadingZeros: true,
+ })
+ ) %
+ (delta + BigInt(1));
+
+ return min + offset;
}
}