Skip to content

Commit

Permalink
make BigInt support only throw if not available when using specific b…
Browse files Browse the repository at this point in the history
…igint functions
  • Loading branch information
peterdemartini committed Oct 13, 2020
1 parent 52c0ca7 commit acc0e52
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion packages/utils/src/numbers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { getTypeOf } from './deps';

let supportsBigInt = true;
try {
if (typeof globalThis.BigInt === 'undefined') {
console.warn('BigInt isn\'t supported in this environment');
supportsBigInt = false;
}
} catch (err) {
console.warn('BigInt isn\'t supported in this environment');
supportsBigInt = false;
}

/** A native implementation of lodash random */
export function random(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
Expand All @@ -24,6 +35,9 @@ export function isBigInt(input: unknown): input is bigint {

/** Convert any input to a bigint */
export function toBigInt(input: unknown): bigint|false {
if (!supportsBigInt) {
throw new Error('BigInt isn\'t supported in this environment');
}
try {
return toBigIntOrThrow(input);
} catch {
Expand All @@ -34,6 +48,9 @@ export function toBigInt(input: unknown): bigint|false {
/** Convert any input to a bigint */
export function toBigIntOrThrow(input: unknown): bigint {
if (isBigInt(input)) return input;
if (!supportsBigInt) {
throw new Error('BigInt isn\'t supported in this environment');
}

if (Number.isSafeInteger(input)) {
return BigInt(input);
Expand All @@ -46,7 +63,10 @@ export function toBigIntOrThrow(input: unknown): bigint {
return BigInt(Number.parseInt(input as any, 10));
}

const _maxBigInt = BigInt(Number.MAX_SAFE_INTEGER);
const _maxBigInt: bigint = supportsBigInt
? BigInt(Number.MAX_SAFE_INTEGER)
: (Number.MAX_SAFE_INTEGER as any);

/**
* Convert a BigInt to either a number of a string
*/
Expand Down

0 comments on commit acc0e52

Please sign in to comment.