Skip to content
This repository has been archived by the owner on Mar 15, 2024. It is now read-only.

Commit

Permalink
perf: faster url parsing
Browse files Browse the repository at this point in the history
`split` creates an array whereas `substring` only involves primitive values.
  • Loading branch information
lachrist committed Feb 22, 2023
1 parent c1ed62e commit e7c92dc
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions components/url/default/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,32 +76,38 @@ export const toDirectoryUrl = (url) => {
}
};

// Alternatively:
// url.match(/:\/{0,2}.*\/([^/#]+)(#.*)?$/)[1]
export const getUrlFilename = (url) => {
const segments = new URL(url).pathname.split("/");
const last = segments[segments.length - 1];
return last === "" ? null : last;
const { pathname } = new URL(url);
if (pathname === "" || pathname.endsWith("/")) {
return null;
} else {
return pathname.substring(pathname.lastIndexOf("/") + 1);
}
};

// Alternatively:
// url.match(/([^.\/]+)(\.[^/#]*)(#.*)?$/)[1]
export const getUrlBasename = (url) => {
const filename = getUrlFilename(url);
if (filename === null) {
return null;
} else if (filename.includes(".")) {
const parts = filename.split(".", 2);
return parts[0];
return filename.substring(0, filename.indexOf("."));
} else {
return filename;
}
};

// Alternatively:
// url.match(/([^.\/]+)(\.[^/#]*)(#.*)?$/)[2]
export const getUrlExtension = (url) => {
const filename = getUrlFilename(url);
if (filename === null) {
return null;
} else if (filename.includes(".")) {
const parts = filename.split(".");
parts[0] = "";
return parts.join(".");
return filename.substring(filename.indexOf("."));
} else {
return null;
}
Expand Down

0 comments on commit e7c92dc

Please sign in to comment.