Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shift try/catch to decode #179

Merged
merged 2 commits into from
Oct 8, 2024
Merged
Changes from 1 commit
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
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 undefined;
}
}

/**
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;
}
}
Loading