added utils functions

This commit is contained in:
Vomitblood 2026-05-01 23:17:21 +08:00
parent 200ff8d580
commit 79ad930ba3

74
src/utils/utils.ts Normal file
View file

@ -0,0 +1,74 @@
// format the date/time
// if the date is today, show the time
export const utilityFormatDate = (dateString: string): string => {
const date = new Date(dateString);
const today = new Date();
// save today date at midnight for comparison
const todayMidnight = new Date(today.getFullYear(), today.getMonth(), today.getDate());
// check if the date is today
if (
date >= todayMidnight &&
date < new Date(todayMidnight.getTime() + 86400000 /* milliseconds in a day sheeesh */)
) {
// show time if today
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
} else {
// "day month year" format
return date.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" });
}
};
// format the file sizes
export const utilityFormatSize = (bytes: number): string => {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
// tf is pow
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};
// UNformat the file sizes
export const utilityUnformatSize = (formattedSize: string): number => {
const sizes = ["Bytes", "KB", "MB", "GB"];
const [value, unit] = formattedSize.split(" ");
const index = sizes.indexOf(unit);
return parseFloat(value) * Math.pow(1024, index);
};
// extract filename and extension from a path
// heeheeheehaw safe coding my boys 🤠
// only consider things after the last period
export const utilityExtractFilename = (filePath: string): { fileStem: string; fileExtension: string } | null => {
const lastSlashIndex = filePath.lastIndexOf("/");
const lastDotIndex = filePath.lastIndexOf(".");
// check if the last slash comes before the last dot
if (lastDotIndex !== -1 && lastSlashIndex > lastDotIndex) {
console.error("Invalid file path: the last slash comes before the last dot");
throw new Error("Invalid file path: the last slash comes before the last dot");
}
// check if the file path ends with a slash
if (lastSlashIndex === filePath.length - 1) {
console.error("Invalid file path: the file path ends with a slash");
throw new Error("Invalid file path: the file path ends with a slash");
}
let fileStem: string, fileExtension: string;
if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) {
// if there's no dot after the last slash, the whole name is the fileStem
fileStem = filePath.substring(lastSlashIndex + 1);
fileExtension = "";
} else {
fileStem = filePath.substring(lastSlashIndex + 1, lastDotIndex);
fileExtension = filePath.substring(lastDotIndex + 1).toLowerCase();
}
return { fileStem: fileStem, fileExtension: fileExtension };
};