diff --git a/javascript/index.js b/javascript/index.js index d0fcca9..63510e2 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -25,7 +25,7 @@ const ELEVATION = 3; const CUSTOM1 = 6; const CUSTOM2 = 7; -const Num = typeof BigInt !== "undefined" ? BigInt : Number; +const Num = (typeof BigInt === "undefined" || (typeof process === "object" ? process : {}).env?.FORCE_NUMBER_TYPE) ? Number : BigInt; function decode(encoded) { const decoder = decodeUnsignedValues(encoded); @@ -77,11 +77,12 @@ function decodeUnsignedValues(encoded) { let result = Num(0); let shift = Num(0); const resList = []; + const mask = Num(0x20); encoded.split('').forEach((char) => { const value = Num(decodeChar(char)); - result |= (value & Num(0x1F)) << shift; - if ((value & Num(0x20)) === Num(0)) { + result += (value % Num(32)) * (Num(2) ** shift); + if ((value % (mask * Num(2))) < mask) { resList.push(result); result = Num(0); shift = Num(0); @@ -111,11 +112,11 @@ function decodeHeader(version, encodedHeader) { function toSigned(val) { // Decode the sign from an unsigned value let res = val; - if (res & Num(1)) { - res = ~res; + if (res % Num(2)) { + res = (res + Num(1)) * Num(-1); } - res >>= Num(1); - return +res.toString(); + res = res / Num(2); + return Math.floor(+res.toString()); } function encode({ precision = DEFAULT_PRECISION, thirdDim = ABSENT, thirdDimPrecision = 0, polyline }) { @@ -171,10 +172,15 @@ function encodeUnsignedNumber(val) { // Uses variable integer encoding to encode an unsigned integer. Returns the encoded string. let res = ''; let numVal = Num(val); + const bigIntSupported = typeof numVal === 'bigint'; while (numVal > 0x1F) { - const pos = (numVal & Num(0x1F)) | Num(0x20); + const pos = (numVal % Num(32)) + Num(32); res += ENCODING_TABLE[pos]; - numVal >>= Num(5); + if (bigIntSupported) { + numVal >>= Num(5); + } else { + numVal = parseInt(numVal / Num(32)); + } } return res + ENCODING_TABLE[numVal]; } @@ -184,9 +190,9 @@ function encodeScaledValue(value) { // `appender` is a callable where the produced chars will land to let numVal = Num(value); const negative = numVal < 0; - numVal <<= Num(1); + numVal = numVal * Num(2); if (negative) { - numVal = ~numVal; + numVal = numVal * Num(-1) - Num(1); } return encodeUnsignedNumber(numVal); diff --git a/javascript/package.json b/javascript/package.json index b4b366a..a18ce6e 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -6,7 +6,7 @@ "types": "index.d.ts", "scripts": { "prepack": "cp ../LICENSE .", - "test": "node test/test.js", + "test": "node test/test.js && FORCE_NUMBER_TYPE=true node test/test.js", "release": "./release.sh" }, "keywords": [