Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

util: Defining common formatter function

CIC4DAefb2a5a38ddd
diff --git a/web/src/util.ts b/web/src/util.ts
index 523d80fd257..515150c08aa 100644
--- a/web/src/util.ts
+++ b/web/src/util.ts
@@ -4,6 +4,7 @@ import * as blueslip from "./blueslip";
import {$t} from "./i18n";
import type {MatchedMessage, Message, RawMessage} from "./message_store";
import type {UpdateMessageEvent} from "./types";
+import {user_settings} from "./user_settings";
// From MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random
export function random_int(min: number, max: number): number {
@@ -489,3 +490,21 @@ export function is_valid_url(url: string, require_absolute = false): boolean {
}
return true;
}
+
+// Formats an array of strings as a Internationalized list using the specified language.
+export function format_array_as_list(
+ array: string[],
+ style: Intl.ListFormatStyle,
+ type: Intl.ListFormatType,
+): string {
+ // If Intl.ListFormat is not supported
+ if (Intl.ListFormat === undefined) {
+ return array.join(", ");
+ }
+
+ // Use Intl.ListFormat to format the array as a Internationalized list.
+ const list_formatter = new Intl.ListFormat(user_settings.default_language, {style, type});
+
+ // Return the formatted string.
+ return list_formatter.format(array);
+}
diff --git a/web/tests/util.test.js b/web/tests/util.test.js
index 419490fb7b9..128cf65af65 100644
--- a/web/tests/util.test.js
+++ b/web/tests/util.test.js
@@ -338,3 +338,16 @@ run_test("is_valid_url", () => {
assert.equal(util.is_valid_url("http://google.com/something?q=query#hash", true), true);
assert.equal(util.is_valid_url("/abc/", true), false);
});
+
+run_test("format_array_as_list", () => {
+ const array = ["apple", "banana", "orange"];
+ // when Intl exist
+ assert.equal(
+ util.format_array_as_list(array, "long", "conjunction"),
+ "apple, banana, and orange",
+ );
+
+ // when Intl.ListFormat does not exist
+ global.Intl.ListFormat = undefined;
+ assert.equal(util.format_array_as_list(array, "long", "conjunction"), "apple, banana, orange");
+});