Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Last active November 2, 2022 05:06
Show Gist options
  • Save danieljpgo/280e87ff64133ba6db1699f9b5c1b14a to your computer and use it in GitHub Desktop.
Save danieljpgo/280e87ff64133ba6db1699f9b5c1b14a to your computer and use it in GitHub Desktop.
/lib
Lib folder that every project needs
/**
* Checks if the code is running in the `browser`.
*/
export function isBrowser() {
return typeof window === "object";
}
/**
* Checks if the code is running in the `server`.
*/
export function isServer() {
return typeof window === "undefined";
}
export function decimalSum(a: number, b: number, positions: number) {
const factor = Math.pow(10, positions);
return (
(Number(a.toFixed(positions)) * factor +
Number(b.toFixed(positions)) * factor) /
factor
);
}
export function decimalSubtract(a: number, b: number, positions: number) {
const factor = Math.pow(10, positions);
return (
(Number(a.toFixed(positions)) * factor -
Number(b.toFixed(positions)) * factor) /
factor
);
}
export function displayDecimal(value: number, positions: number) {
return (Math.round(value * 100) / 100).toFixed(positions);
}
// @TODO: check if it is running on the client
/**
* Returns the current object from `localStorage` associated with the given `key`.
*/
export function getLocalStorageData<T = unknown>(key: string): T | undefined {
const data = window.localStorage.getItem(key);
try {
return data ? JSON.parse(data) : undefined;
} catch {
return undefined;
}
}
/**
* Save the value to `localStorage` associated with the given `key`.
*/
export function setLocalStorageData<T = unknown>(key: string, body: T) {
window.localStorage.setItem(key, JSON.stringify(body));
}
/**
* Remove the value from `localStorage` associated with the given `key`.
*/
export function removeLocalStorageData(key: string) {
window.localStorage.removeItem(key);
}
/**
* Create a response with a permanently redirect using `301` as status code.
*/
export function redirectPermanently(
url: string,
init?: Omit<ResponseInit, "status">
) {
return redirect(url, { ...init, status: 301 });
}
/**
* Create a response with a Not Found error using `404` as status code.
*/
export function notFound(init?: Omit<ResponseInit, "status">) {
return json("Not Found", { ...init, status: 404 });
}
/**
* Create a response receiving a JSON object with the status code 400.
*/
export function badRequest<Data = unknown>(
data: Data,
init?: Omit<ResponseInit, "status">
) {
return json<Data>(data, { ...init, status: 400 });
}
/**
* Compose classnames dynamically.
*/
export function cn(...classes: string[]) {
return classes.filter(Boolean).join(" ");
}
export type LooseAutocomplete<T extends string> = T | Omit<string, T>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment