import { browser } from "$app/environment"; import type { AxiosHeaders, AxiosRequestConfig } from "axios"; import jwtDecode from "jwt-decode"; import { refreshRequest } from "../requests/auth.request"; export const compareObject = (obj1: object, obj2: object) => { const keys = Object.keys(obj1); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const v1 = obj1[key as keyof typeof obj1]; const v2 = obj2[key as keyof typeof obj2]; if (v1 != undefined && v2 != undefined) { if (v1 != v2) { return false; } } } return true; }; export const checkExpire = (exp: number) => { return Date.now() >= exp * 1000; }; export const parseTimer = (tps: number) => { const remainder = Math.abs(tps) / 60; const min = Math.floor(remainder); const sec = Math.abs(tps) - 60 * min; return `${tps < 0 ? "+ ": ""}${String(min).length == 1 && min > 0 ? '0' : ''}${min > 0 ? String(min) + " : ": ""}${ String(sec).length == 1 ? '0' : '' }${sec}s`; }; export const autoRefresh = async (config: AxiosRequestConfig) => { if (!browser || config.url?.includes('/refresh')) return config let access = localStorage.getItem('token'); const refresh = localStorage.getItem('refresh'); if(access == null) return config const { exp } = jwtDecode<{exp: number}>(access); if (refresh != null && checkExpire(exp)) { access = await refreshRequest(refresh).then((r) => { localStorage.setItem('token', r.access_token); return r.access_token }).catch(()=>access) } (config.headers as AxiosHeaders).set("Authorization", `Bearer ${access}`) return config; }; export const average = (arr: Array) => { return arr.reduce((partialSum, a) => partialSum + a, 0) / arr.length; }; export const statsCalculator = (arr: Array) => { return { avg: average(arr), min: Math.min(...arr), max: Math.max(...arr) }; }; export const color = [ // "blanc", "marron", "violet", "jaune", "orange", "bleu", "vert", "noir", "rouge", "rose", ]; export const colorCode = { //blanc: "rgb(255,255,255)", bleu: "rgb(51,123,255)", vert: "rgb(0,204,0)", rouge: "rgb(255,0,0)", marron: "rgb(153,76,0)", violet: "rgb(204,0,204)", jaune: "rgb(255,255,0)", orange: "rgb(255,128,0)", noir: "rgb(10,10,10)", rose: "rgb(255,102,255)", blanc: "rgb(240,240,240)", blanche: "rgb(240,240,240)", }; export const getColorCode = (c: string)=>{ // if color contains a substring in colorCode for (const key in colorCode) { if (c.includes(key)) { return colorCode[key as keyof typeof colorCode]; } } //random color in colorCode const keys = Object.keys(colorCode) return colorCode[keys[keys.length * Math.random() << 0]]; }