Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions javascript/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 }) {
Expand Down Expand Up @@ -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];
}
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion javascript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down