forked from pinks/eris
1
0
Fork 0
nyx/intl.ts

44 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-09-04 16:55:48 +00:00
import { FormattedString } from "./deps.ts";
export function formatOrdinal(n: number) {
if (n % 100 === 11 || n % 100 === 12 || n % 100 === 13) return `${n}th`;
if (n % 10 === 1) return `${n}st`;
if (n % 10 === 2) return `${n}nd`;
if (n % 10 === 3) return `${n}rd`;
return `${n}th`;
}
2023-09-06 00:53:34 +00:00
type DeepArray<T> = Array<T | DeepArray<T>>;
type StringLikes = DeepArray<FormattedString | string | number | null | undefined>;
2023-09-04 16:55:48 +00:00
/**
2023-09-06 00:53:34 +00:00
* Like `fmt` from `grammy_parse_mode` but additionally accepts arrays.
2023-09-04 16:55:48 +00:00
* @see https://deno.land/x/grammy_parse_mode@1.7.1/format.ts?source=#L182
*/
2023-09-06 00:53:34 +00:00
export const fmt = (
rawStringParts: TemplateStringsArray | StringLikes,
...stringLikes: StringLikes
): FormattedString => {
2023-09-04 16:55:48 +00:00
let text = "";
2023-09-06 00:53:34 +00:00
const entities: ConstructorParameters<typeof FormattedString>[1][] = [];
const length = Math.max(rawStringParts.length, stringLikes.length);
for (let i = 0; i < length; i++) {
for (let stringLike of [rawStringParts[i], stringLikes[i]]) {
if (Array.isArray(stringLike)) {
stringLike = fmt(stringLike);
}
if (stringLike instanceof FormattedString) {
entities.push(
...stringLike.entities.map((e) => ({
...e,
offset: e.offset + text.length,
})),
);
}
if (stringLike != null) text += stringLike.toString();
}
2023-09-04 16:55:48 +00:00
}
return new FormattedString(text, entities);
2023-09-06 00:53:34 +00:00
};