Skip to content

Commit 9e605e3

Browse files
committed
port MiscUtil from Chewbotcca
1 parent 6c3a616 commit 9e605e3

File tree

1 file changed

+209
-0
lines changed

1 file changed

+209
-0
lines changed
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/*
2+
* Copyright (C) 2024 Chewbotcca
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU General Public License as published by
6+
* the Free Software Foundation, either version 3 of the License, or
7+
* (at your option) any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU General Public License
15+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
16+
*/
17+
package pw.chew.chewbotcca.util;
18+
19+
import net.dv8tion.jda.api.entities.User;
20+
import org.json.JSONArray;
21+
import org.json.JSONObject;
22+
23+
import java.text.DecimalFormat;
24+
import java.text.NumberFormat;
25+
import java.time.OffsetDateTime;
26+
import java.time.format.DateTimeFormatter;
27+
import java.util.ArrayList;
28+
import java.util.Collections;
29+
import java.util.LinkedHashMap;
30+
import java.util.List;
31+
import java.util.Locale;
32+
import java.util.Map;
33+
import java.util.random.RandomGenerator;
34+
35+
/**
36+
* A collection of misc utilities used throughout the bot
37+
*/
38+
public class MiscUtil {
39+
private static final RandomGenerator RANDOM = RandomGenerator.getDefault();
40+
41+
/**
42+
* Gets a random item from an array
43+
*
44+
* @param array the array
45+
* @return a random value from the array
46+
*/
47+
@SafeVarargs
48+
public static <T> T getRandom(T... array) {
49+
return array[RANDOM.nextInt(array.length)];
50+
}
51+
52+
/**
53+
* Sorts a given map of objects by their value
54+
*
55+
* @param map the map to sort
56+
* @param <K> key
57+
* @param <V> value (to sort by)
58+
* @return a sorted map
59+
*/
60+
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
61+
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
62+
list.sort(Map.Entry.comparingByValue());
63+
Collections.reverse(list);
64+
65+
Map<K, V> result = new LinkedHashMap<>();
66+
for (Map.Entry<K, V> entry : list) {
67+
result.put(entry.getKey(), entry.getValue());
68+
}
69+
70+
return result;
71+
}
72+
73+
/**
74+
* <a href="https://github.com/ChewMC/TransmuteIt/blob/2b86/src/pw/chew/transmuteit/DiscoveriesCommand.java#L174-L186">Source</a><br>
75+
* Capitalizes a String, e.g. "BRUH_MOMENT" -> "Bruh Moment"
76+
*
77+
* @param to the unformatted string
78+
* @return a formatting string
79+
* @author Chew
80+
*/
81+
public static String capitalize(String to) {
82+
if (to.isBlank()) {
83+
return "";
84+
}
85+
String[] words = to.split("_");
86+
StringBuilder newword = new StringBuilder();
87+
for (String word : words) {
88+
String rest = word.substring(1).toLowerCase();
89+
String first = word.substring(0, 1).toUpperCase();
90+
newword.append(first).append(rest).append(" ");
91+
}
92+
return newword.toString().trim();
93+
}
94+
95+
/**
96+
* Converts a given amount of bytes into friendlier data.<br>
97+
* Example: 2048 => 2 KB
98+
*
99+
* @param bytes the amount of bytes
100+
* @return the formatted string
101+
*/
102+
public static String bytesToFriendly(long bytes) {
103+
// Find size of repo and list it
104+
int k = 1024;
105+
String[] measure = {"B", "KB", "MB", "GB", "TB"};
106+
double i;
107+
if (bytes == 0) {
108+
i = 0;
109+
} else {
110+
i = Math.floor(Math.log(bytes) / Math.log(k));
111+
}
112+
DecimalFormat df = new DecimalFormat("#.##");
113+
return df.format(bytes / Math.pow(k, i)) + " " + measure[(int) i + 1];
114+
}
115+
116+
/**
117+
* Parse a given date with a given format
118+
*
119+
* @param date The date string to parse
120+
* @param format The format to parse
121+
* @return the parsed date
122+
*/
123+
public static OffsetDateTime dateParser(String date, String format) {
124+
return OffsetDateTime.parse(date, DateTimeFormatter.ofPattern(format));
125+
}
126+
127+
/**
128+
* Parse a given date with a given format
129+
*
130+
* @param date The date string to parse
131+
* @param format The format to parse
132+
* @return the parsed date
133+
*/
134+
public static OffsetDateTime dateParser(String date, DateTimeFormatter format) {
135+
return OffsetDateTime.parse(date, format);
136+
}
137+
138+
/**
139+
* Delimits a value into common "1,000,000.00" (US) format.
140+
*
141+
* @param value The value
142+
* @return A delimited string
143+
*/
144+
public static String delimitNumber(long value) {
145+
return NumberFormat.getNumberInstance(Locale.US).format(value);
146+
}
147+
148+
/**
149+
* Formats a percentage based on a decimal value.
150+
* E.g. 0.05 => 5%
151+
*
152+
* @param value The value
153+
* @return A percentage
154+
*/
155+
public static String formatPercent(float value) {
156+
DecimalFormat df = new DecimalFormat("#.##");
157+
return df.format(value * 100) + "%";
158+
}
159+
160+
/**
161+
* Converts a JSONArray to a list of {@code <T>}.
162+
*
163+
* @param array The JSONArray
164+
* @param cast The class to cast to
165+
* @param <T> The type to cast to
166+
* @return A list of {@code <T>}
167+
*/
168+
public static <T> List<T> toList(JSONArray array, Class<T> cast) {
169+
List<T> results = new ArrayList<>(array.length());
170+
for (Object element : array) {
171+
if (element == null || JSONObject.NULL.equals(element)) {
172+
results.add(null);
173+
} else {
174+
results.add(cast.cast(element));
175+
}
176+
}
177+
return results;
178+
}
179+
180+
/**
181+
* Returns the tag of a user. If they have a discriminator, it'll be username#0000, otherwise, it'll be their username.
182+
*
183+
* @param user the user
184+
* @return the user's tag
185+
*/
186+
public static String getTag(User user) {
187+
if (user.getDiscriminator().equals("0000")) {
188+
return user.getName();
189+
} else {
190+
return user.getAsTag();
191+
}
192+
}
193+
194+
public static int asInt(String s) {
195+
try {
196+
return Integer.parseInt(s);
197+
} catch (NumberFormatException e) {
198+
return 0;
199+
}
200+
}
201+
202+
public static long asLong(String s) {
203+
try {
204+
return Long.parseLong(s);
205+
} catch (NumberFormatException e) {
206+
return 0;
207+
}
208+
}
209+
}

0 commit comments

Comments
 (0)