aboutsummaryrefslogtreecommitdiff
path: root/src/utils/text.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/text.ts')
-rw-r--r--src/utils/text.ts25
1 files changed, 25 insertions, 0 deletions
diff --git a/src/utils/text.ts b/src/utils/text.ts
index 17826e8..fae3343 100644
--- a/src/utils/text.ts
+++ b/src/utils/text.ts
@@ -16,6 +16,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
+import { moment } from "@webpack/common";
+
// Utils for readable text transformations eg: `toTitle(fromKebab())`
// Case style to words
@@ -34,3 +36,26 @@ export const wordsToPascal = (words: string[]) =>
words.map(w => w[0].toUpperCase() + w.slice(1)).join("");
export const wordsToTitle = (words: string[]) =>
words.map(w => w[0].toUpperCase() + w.slice(1)).join(" ");
+
+/**
+ * Forms milliseconds into a human readable string link "1 day, 2 hours, 3 minutes and 4 seconds"
+ * @param ms Milliseconds
+ * @param short Whether to use short units like "d" instead of "days"
+ */
+export function formatDuration(ms: number, short: boolean = false) {
+ const dur = moment.duration(ms);
+ return (["years", "months", "weeks", "days", "hours", "minutes", "seconds"] as const).reduce((res, unit) => {
+ const x = dur[unit]();
+ if (x > 0 || res.length) {
+ if (res.length)
+ res += unit === "seconds" ? " and " : ", ";
+
+ const unitStr = short
+ ? unit[0]
+ : x === 1 ? unit.slice(0, -1) : unit;
+
+ res += `${x} ${unitStr}`;
+ }
+ return res;
+ }, "").replace(/((,|and) \b0 \w+)+$/, "") || "now";
+}