/ src / lib / utils.ts
utils.ts
 1  import { type ClassValue, clsx } from "clsx";
 2  import { twMerge } from "tailwind-merge";
 3  
 4  export function cn(...inputs: ClassValue[]) {
 5    return twMerge(clsx(inputs));
 6  }
 7  
 8  export function shortenEthAddress(address: string): string {
 9    if (!address || address.length !== 42) {
10      throw new Error("Invalid Ethereum address");
11    }
12  
13    const start = address.slice(0, 6);
14    const end = address.slice(-4);
15  
16    return `${start}...${end}`;
17  }
18  
19  export function formatNumber(value: number): string {
20    if (Math.abs(value) < 1) {
21      return value.toFixed(5);
22    }
23  
24    if (Math.abs(value) < 1000) {
25      return value.toFixed(2);
26    }
27  
28    const suffixes = ["", "k", "M", "B", "T"];
29    const suffixIndex = Math.floor(Math.log10(Math.abs(value)) / 3);
30    const scaledValue = value / Math.pow(10, suffixIndex * 3);
31  
32    if (suffixIndex === 0) {
33      return value.toFixed(0);
34    }
35  
36    const formattedValue = scaledValue.toFixed(2);
37    const suffix = suffixes[suffixIndex];
38    return `${formattedValue}${suffix}`;
39  }
40  
41  export function formatPercentage(value: number): string {
42    const percentage = (value - 1) * 100;
43    const formattedPercentage = percentage.toFixed(2);
44    return `${formattedPercentage}%`;
45  }
46  
47  export function getColoredText(numStr: string) {
48    const upperLimit = 200;
49    const lowerLimit = -50;
50  
51    let num = parseFloat(numStr.replace("%", ""));
52    if (num > upperLimit) num = upperLimit;
53    if (num < lowerLimit) num = lowerLimit;
54  
55    let color;
56  
57    // Determine the color based on the input number
58    if (num >= 0 && num <= upperLimit) {
59      // Dark green to light green (logarithmic scaling)
60      const greenValue =
61        220 - Math.floor((220 * Math.log(num + 1)) / Math.log(upperLimit + 1));
62      color = `rgb(${greenValue}, 255, ${greenValue})`;
63    } else if (num >= lowerLimit && num < 0) {
64      // Dark red to light red (logarithmic scaling)
65      const redValue =
66        220 - Math.floor((220 * Math.log(-num + 1)) / Math.log(-lowerLimit + 1));
67      color = `rgb(255, ${redValue}, ${redValue})`;
68    } else {
69      // Default color (white)
70      color = "rgb(255, 255, 255)";
71    }
72  
73    // Return the colored text as an HTML string with Tailwind classes
74    return color;
75  }
76  
77  export function removeUnderscores(text: string) {
78    return text.replace(/_/g, "");
79  }