util: Defining common formatter function

This commit is contained in:
CIC4DA 2024-01-05 19:52:54 +05:30 committed by Tim Abbott
parent e2520da24d
commit efb2a5a38d
2 changed files with 32 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import * as blueslip from "./blueslip";
import {$t} from "./i18n"; import {$t} from "./i18n";
import type {MatchedMessage, Message, RawMessage} from "./message_store"; import type {MatchedMessage, Message, RawMessage} from "./message_store";
import type {UpdateMessageEvent} from "./types"; 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 // From MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random
export function random_int(min: number, max: number): number { 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; 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);
}

View File

@ -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("http://google.com/something?q=query#hash", true), true);
assert.equal(util.is_valid_url("/abc/", true), false); 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");
});