Skip to content

Commit

Permalink
apply prettier format to utils.ts as an example file
Browse files Browse the repository at this point in the history
  • Loading branch information
flx-sta committed Jun 11, 2024
1 parent 350e3ee commit a10289f
Showing 1 changed file with 89 additions and 78 deletions.
167 changes: 89 additions & 78 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { MoneyFormat } from "./enums/money-format";
export const MissingTextureKey = "__MISSING";

export function toReadableString(str: string): string {
return str.replace(/\_/g, " ").split(" ").map(s => `${s.slice(0, 1)}${s.slice(1).toLowerCase()}`).join(" ");
return str
.replace(/\_/g, " ")
.split(" ")
.map((s) => `${s.slice(0, 1)}${s.slice(1).toLowerCase()}`)
.join(" ");
}

export function randomString(length: integer, seeded: boolean = false) {
Expand Down Expand Up @@ -71,10 +75,10 @@ export function padInt(value: integer, length: integer, padWith?: string): strin
}

/**
* Returns a random integer between min and min + range
* @param range The amount of possible numbers
* @param min The starting number
*/
* Returns a random integer between min and min + range
* @param range The amount of possible numbers
* @param min The starting number
*/
export function randInt(range: integer, min: integer = 0): integer {
if (range === 1) {
return min;
Expand All @@ -86,34 +90,28 @@ export function randSeedInt(range: integer, min: integer = 0): integer {
if (range <= 1) {
return min;
}
return Phaser.Math.RND.integerInRange(min, (range - 1) + min);
return Phaser.Math.RND.integerInRange(min, range - 1 + min);
}

/**
* Returns a random integer between min and max (non-inclusive)
* @param min The lowest number
* @param max The highest number
*/
* Returns a random integer between min and max (non-inclusive)
* @param min The lowest number
* @param max The highest number
*/
export function randIntRange(min: integer, max: integer): integer {
return randInt(max - min, min);
}

export function randItem<T>(items: T[]): T {
return items.length === 1
? items[0]
: items[randInt(items.length)];
return items.length === 1 ? items[0] : items[randInt(items.length)];
}

export function randSeedItem<T>(items: T[]): T {
return items.length === 1
? items[0]
: Phaser.Math.RND.pick(items);
return items.length === 1 ? items[0] : Phaser.Math.RND.pick(items);
}

export function randSeedWeightedItem<T>(items: T[]): T {
return items.length === 1
? items[0]
: Phaser.Math.RND.weightedPick(items);
return items.length === 1 ? items[0] : Phaser.Math.RND.weightedPick(items);
}

export function randSeedEasedWeightedItem<T>(items: T[], easingFunction: string = "Sine.easeIn"): T {
Expand Down Expand Up @@ -151,15 +149,15 @@ export function getFrameMs(frameCount: integer): integer {

export function getCurrentTime(): number {
const date = new Date();
return (((date.getHours() * 60 + date.getMinutes()) / 1440) + 0.675) % 1;
return ((date.getHours() * 60 + date.getMinutes()) / 1440 + 0.675) % 1;
}

const secondsInHour = 3600;

export function getPlayTimeString(totalSeconds: integer): string {
const days = `${Math.floor(totalSeconds / (secondsInHour * 24))}`;
const hours = `${Math.floor(totalSeconds % (secondsInHour * 24) / secondsInHour)}`;
const minutes = `${Math.floor(totalSeconds % secondsInHour / 60)}`;
const hours = `${Math.floor((totalSeconds % (secondsInHour * 24)) / secondsInHour)}`;
const minutes = `${Math.floor((totalSeconds % secondsInHour) / 60)}`;
const seconds = `${Math.floor(totalSeconds % 60)}`;

return `${days.padStart(2, "0")}:${hours.padStart(2, "0")}:${minutes.padStart(2, "0")}:${seconds.padStart(2, "0")}`;
Expand Down Expand Up @@ -198,7 +196,7 @@ export function getIvsFromId(id: integer): integer[] {
binToDec(decToBin(id).substring(10, 15)),
binToDec(decToBin(id).substring(15, 20)),
binToDec(decToBin(id).substring(20, 25)),
binToDec(decToBin(id).substring(25, 30))
binToDec(decToBin(id).substring(25, 30)),
];
}

Expand Down Expand Up @@ -252,7 +250,7 @@ export function formatFancyLargeNumber(number: number, rounded: number = 3): str
number /= Math.pow(1000, exponent);
}

return `${(exponent === 0) || number % 1 === 0 ? number : number.toFixed(rounded)}${AbbreviationsLargeNumber[exponent]}`;
return `${exponent === 0 || number % 1 === 0 ? number : number.toFixed(rounded)}${AbbreviationsLargeNumber[exponent]}`;
}

export function formatMoney(format: MoneyFormat, amount: number) {
Expand All @@ -267,25 +265,30 @@ export function formatStat(stat: integer, forHp: boolean = false): string {
}

export function getEnumKeys(enumType): string[] {
return Object.values(enumType).filter(v => isNaN(parseInt(v.toString()))).map(v => v.toString());
return Object.values(enumType)
.filter((v) => isNaN(parseInt(v.toString())))
.map((v) => v.toString());
}

export function getEnumValues(enumType): integer[] {
return Object.values(enumType).filter(v => !isNaN(parseInt(v.toString()))).map(v => parseInt(v.toString()));
return Object.values(enumType)
.filter((v) => !isNaN(parseInt(v.toString())))
.map((v) => parseInt(v.toString()));
}

export function executeIf<T>(condition: boolean, promiseFunc: () => Promise<T>): Promise<T> {
return condition ? promiseFunc() : new Promise<T>(resolve => resolve(null));
return condition ? promiseFunc() : new Promise<T>((resolve) => resolve(null));
}

export const sessionIdKey = "pokerogue_sessionId";
// Check if the current hostname is 'localhost' or an IP address, and ensure a port is specified
export const isLocal = (
(window.location.hostname === "localhost" ||
/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(window.location.hostname)) &&
window.location.port !== "") || window.location.hostname === "";
export const isLocal =
((window.location.hostname === "localhost" || /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(window.location.hostname)) &&
window.location.port !== "") ||
window.location.hostname === "";

export const localServerUrl = import.meta.env.VITE_SERVER_URL ?? `http://${window.location.hostname}:${window.location.port+1}`;
export const localServerUrl =
import.meta.env.VITE_SERVER_URL ?? `http://${window.location.hostname}:${window.location.port + 1}`;

// Set the server URL based on whether it's local or not
export const serverUrl = isLocal ? localServerUrl : "";
Expand All @@ -295,7 +298,7 @@ export let isLocalServerConnected = true;

export function setCookie(cName: string, cValue: string): void {
const expiration = new Date();
expiration.setTime(new Date().getTime() + 3600000 * 24 * 30 * 3/*7*/);
expiration.setTime(new Date().getTime() + 3600000 * 24 * 30 * 3 /*7*/);
document.cookie = `${cName}=${cValue};Secure;SameSite=Strict;Path=/;Expires=${expiration.toUTCString()}`;
}

Expand All @@ -321,44 +324,53 @@ export function getCookie(cName: string): string {
*/
export function localPing() {
if (isLocal) {
apiFetch("game/titlestats")
.then(resolved => isLocalServerConnected = true,
rejected => isLocalServerConnected = false
);
apiFetch("game/titlestats").then(
(resolved) => (isLocalServerConnected = true),
(rejected) => (isLocalServerConnected = false),
);
}
}

export function apiFetch(path: string, authed: boolean = false): Promise<Response> {
return (isLocal && isLocalServerConnected) || !isLocal ? new Promise((resolve, reject) => {
const request = {};
if (authed) {
const sId = getCookie(sessionIdKey);
if (sId) {
request["headers"] = { "Authorization": sId };
return (isLocal && isLocalServerConnected) || !isLocal
? new Promise((resolve, reject) => {
const request = {};
if (authed) {
const sId = getCookie(sessionIdKey);
if (sId) {
request["headers"] = { Authorization: sId };
}
}
}
fetch(`${apiUrl}/${path}`, request)
.then(response => resolve(response))
.catch(err => reject(err));
}) : new Promise(() => {});
}

export function apiPost(path: string, data?: any, contentType: string = "application/json", authed: boolean = false): Promise<Response> {
return (isLocal && isLocalServerConnected) || !isLocal ? new Promise((resolve, reject) => {
const headers = {
"Accept": contentType,
"Content-Type": contentType,
};
if (authed) {
const sId = getCookie(sessionIdKey);
if (sId) {
headers["Authorization"] = sId;
fetch(`${apiUrl}/${path}`, request)
.then((response) => resolve(response))
.catch((err) => reject(err));
})
: new Promise(() => {});
}

export function apiPost(
path: string,
data?: any,
contentType: string = "application/json",
authed: boolean = false,
): Promise<Response> {
return (isLocal && isLocalServerConnected) || !isLocal
? new Promise((resolve, reject) => {
const headers = {
Accept: contentType,
"Content-Type": contentType,
};
if (authed) {
const sId = getCookie(sessionIdKey);
if (sId) {
headers["Authorization"] = sId;
}
}
}
fetch(`${apiUrl}/${path}`, { method: "POST", headers: headers, body: data })
.then(response => resolve(response))
.catch(err => reject(err));
}) : new Promise(() => {});
fetch(`${apiUrl}/${path}`, { method: "POST", headers: headers, body: data })
.then((response) => resolve(response))
.catch((err) => reject(err));
})
: new Promise(() => {});
}

export class BooleanHolder {
Expand Down Expand Up @@ -396,8 +408,8 @@ export function fixedInt(value: integer): integer {
export function rgbToHsv(r: integer, g: integer, b: integer) {
const v = Math.max(r, g, b);
const c = v - Math.min(r, g, b);
const h = c && ((v === r) ? (g - b) / c : ((v === g) ? 2 + (b - r) / c : 4 + (r - g) / c));
return [ 60 * (h < 0 ? h + 6 : h), v && c / v, v];
const h = c && (v === r ? (g - b) / c : v === g ? 2 + (b - r) / c : 4 + (r - g) / c);
return [60 * (h < 0 ? h + 6 : h), v && c / v, v];
}

/**
Expand All @@ -406,14 +418,14 @@ export function rgbToHsv(r: integer, g: integer, b: integer) {
* @param {Array} rgb2 Second RGB color in array
*/
export function deltaRgb(rgb1: integer[], rgb2: integer[]): integer {
const [ r1, g1, b1 ] = rgb1;
const [ r2, g2, b2 ] = rgb2;
const [r1, g1, b1] = rgb1;
const [r2, g2, b2] = rgb2;
const drp2 = Math.pow(r1 - r2, 2);
const dgp2 = Math.pow(g1 - g2, 2);
const dbp2 = Math.pow(b1 - b2, 2);
const t = (r1 + r2) / 2;

return Math.ceil(Math.sqrt(2 * drp2 + 4 * dgp2 + 3 * dbp2 + t * (drp2 - dbp2) / 256));
return Math.ceil(Math.sqrt(2 * drp2 + 4 * dgp2 + 3 * dbp2 + (t * (drp2 - dbp2)) / 256));
}

export function rgbHexToRgba(hex: string) {
Expand All @@ -422,7 +434,7 @@ export function rgbHexToRgba(hex: string) {
r: parseInt(color[1], 16),
g: parseInt(color[2], 16),
b: parseInt(color[3], 16),
a: 255
a: 255,
};
}

Expand Down Expand Up @@ -462,12 +474,13 @@ export function verifyLang(lang?: string): boolean {
* @param container container with game objects inside it
*/
export function printContainerList(container: Phaser.GameObjects.Container): void {
console.log(container.list.map(go => {
return {type: go.type, name: go.name};
}));
console.log(
container.list.map((go) => {
return { type: go.type, name: go.name };
}),
);
}


/**
* Truncate a string to a specified maximum length and add an ellipsis if it exceeds that length.
*
Expand Down Expand Up @@ -506,9 +519,7 @@ export function reverseValueToKeySetting(input) {
// Split the input string into an array of words
const words = input.split(" ");
// Capitalize the first letter of each word and convert the rest to lowercase
const capitalizedWords = words.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
const capitalizedWords = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
// Join the capitalized words with underscores and return the result
return capitalizedWords.join("_");
}


0 comments on commit a10289f

Please sign in to comment.