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.ts39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/utils/text.ts b/src/utils/text.ts
index 115b3e2..63f6007 100644
--- a/src/utils/text.ts
+++ b/src/utils/text.ts
@@ -92,3 +92,42 @@ export function formatDuration(time: number, unit: Units, short: boolean = false
return res.length ? res : `0 ${getUnitStr(unit, false, short)}`;
}
+
+/**
+ * Join an array of strings in a human readable way (1, 2 and 3)
+ * @param elements Elements
+ */
+export function humanFriendlyJoin(elements: string[]): string;
+/**
+ * Join an array of strings in a human readable way (1, 2 and 3)
+ * @param elements Elements
+ * @param mapper Function that converts elements to a string
+ */
+export function humanFriendlyJoin<T>(elements: T[], mapper: (e: T) => string): string;
+export function humanFriendlyJoin(elements: any[], mapper: (e: any) => string = s => s): string {
+ const { length } = elements;
+ if (length === 0)
+ return "";
+ if (length === 1)
+ return mapper(elements[0]);
+
+ let s = "";
+
+ for (let i = 0; i < length; i++) {
+ s += mapper(elements[i]);
+ if (length - i > 2)
+ s += ", ";
+ else if (length - i > 1)
+ s += " and ";
+ }
+
+ return s;
+}
+
+/**
+ * Wrap the text in ``` with an optional language
+ */
+export function makeCodeblock(text: string, language?: string) {
+ const chars = "```";
+ return `${chars}${language || ""}\n${text.replaceAll("```", "\\`\\`\\`")}\n${chars}`;
+}