From efb2a5a38ddd4808571173ec783af94a981348d5 Mon Sep 17 00:00:00 2001 From: CIC4DA Date: Fri, 5 Jan 2024 19:52:54 +0530 Subject: [PATCH] util: Defining common formatter function --- web/src/util.ts | 19 +++++++++++++++++++ web/tests/util.test.js | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/web/src/util.ts b/web/src/util.ts index 523d80fd25..515150c08a 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 419490fb7b..128cf65af6 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"); +});