From ec817f3c6cfa51de4653c92778b61a3fe1f4a9e9 Mon Sep 17 00:00:00 2001 From: Daniel Meyer <8926560+pubkey@users.noreply.github.com> Date: Fri, 15 Dec 2023 04:31:31 +0100 Subject: [PATCH] fix: BigInt not always available (#407) Selectively add BigInt for supported platforms. --- src/util.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/util.ts b/src/util.ts index 47263648f..fb10199d5 100644 --- a/src/util.ts +++ b/src/util.ts @@ -87,7 +87,6 @@ const STRING_CONVERTERS = new Map>([ [RegExp, toString], [Function, toString], [Symbol, toString], - [BigInt, (n: bigint) => "0x" + n.toString(16)], [Date, (d: Date) => d.toISOString()], [String, JSON.stringify], [Null, (_: AnyVal) => "null"], @@ -100,10 +99,22 @@ const STRING_CONVERTERS = new Map>([ [Int32Array, typedArrayToString], [Uint32Array, typedArrayToString], [Float32Array, typedArrayToString], - [Float64Array, typedArrayToString], - [BigInt64Array, typedArrayToString], - [BigUint64Array, typedArrayToString] + [Float64Array, typedArrayToString] ]); +/** + * Some types like BigInt are not available on more exotic + * JavaScript runtimes like ReactNative or QuickJS. + * So we fill them in only if they exist so that it does not throw an error. + */ +if (typeof BigInt !== "undefined") { + STRING_CONVERTERS.set(BigInt, (n: bigint) => "0x" + n.toString(16)); +} +if (typeof BigInt64Array !== "undefined") { + STRING_CONVERTERS.set(BigInt64Array, typedArrayToString); +} +if (typeof BigUint64Array !== "undefined") { + STRING_CONVERTERS.set(BigUint64Array, typedArrayToString); +} /** MongoDB sort comparison order. https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order */ const SORT_ORDER_BY_TYPE: Record = {