From 93a5b97e3eb545ab39910bf07fb3249d9610e1b0 Mon Sep 17 00:00:00 2001 From: Blake Embrey Date: Tue, 8 Oct 2024 11:35:18 -0700 Subject: [PATCH] Shift try/catch to decode (#179) --- src/index.ts | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/src/index.ts b/src/index.ts index 3d572dd..b572fab 100644 --- a/src/index.ts +++ b/src/index.ts @@ -82,7 +82,7 @@ export interface ParseOptions { * * @default decodeURIComponent */ - decode?: (str: string) => string; + decode?: (str: string) => string | undefined; } /** @@ -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; @@ -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; + } } /** @@ -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; - } -}