Skip to content

Commit

Permalink
Shift try/catch to decode (#179)
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey authored Oct 8, 2024
1 parent 0f56c6e commit 93a5b97
Showing 1 changed file with 11 additions and 16 deletions.
27 changes: 11 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export interface ParseOptions {
*
* @default decodeURIComponent
*/
decode?: (str: string) => string;
decode?: (str: string) => string | undefined;
}

/**
Expand Down Expand Up @@ -133,8 +133,8 @@ export function parse(
valEndIdx--;
}

const val = str.slice(valStartIdx, valEndIdx);
obj[key] = tryDecode(val, dec);
const value = dec(str.slice(valStartIdx, valEndIdx));
if (value !== undefined) obj[key] = value;
}

index = endIdx + 1;
Expand Down Expand Up @@ -366,8 +366,14 @@ export function serialize(
/**
* URL-decode string value. Optimized to skip native call when no %.
*/
function decode(str: string): string {
return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
function decode(str: string): string | undefined {
if (str.indexOf("%") === -1) return str;

try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}

/**
Expand All @@ -376,14 +382,3 @@ function decode(str: string): string {
function isDate(val: any): val is Date {
return __toString.call(val) === "[object Date]";
}

/**
* Try decoding a string using a decoding function.
*/
function tryDecode(str: string, decode: (str: string) => string): string {
try {
return decode(str);
} catch (e) {
return str;
}
}

0 comments on commit 93a5b97

Please sign in to comment.