Skip to content

Commit 5dbd2df

Browse files
committed
perf: faster encode_url and decode_url
1 parent 23521a6 commit 5dbd2df

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

lib/decode_url.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
1-
import { parse, format } from 'url';
1+
import { format } from 'url';
22
import { unescape } from 'querystring';
33

4+
const PROTOCOL_RE = /^[a-z0-9.+-]+:/i;
5+
6+
const hasProtocolLikeNode = (str: unknown): boolean => {
7+
if (typeof str !== 'string') throw new TypeError('url must be a string');
8+
return PROTOCOL_RE.test(str.trim());
9+
};
10+
411
const decodeURL = (str: string) => {
5-
if (parse(str).protocol) {
12+
if (hasProtocolLikeNode(str)) {
613
const parsed = new URL(str);
714

815
// Exit if input is a data url

lib/encode_url.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
1-
import { parse, format } from 'url';
1+
import { format } from 'url';
22
import { unescape } from 'querystring';
33

4+
const PROTOCOL_RE = /^[a-z0-9.+-]+:/i;
5+
6+
const hasProtocolLikeNode = (str: unknown): boolean => {
7+
if (typeof str !== 'string') throw new TypeError('url must be a string');
8+
return PROTOCOL_RE.test(str.trim());
9+
};
10+
411
const encodeURL = (str: string) => {
5-
if (parse(str).protocol) {
12+
if (hasProtocolLikeNode(str)) {
613
const parsed = new URL(str);
714

815
// Exit if input is a data url

0 commit comments

Comments
 (0)