Back
Version 5
2/25/2024
type TextAlts = { text: string } & Partial<Record<string, string>>;
export function textAlts<R extends TextAlts = { text: string }>(
strings: TemplateStringsArray,
...replacements: (string | R)[]
) {
return strings.reduce((res, string, index) => {
let toAdd = { text: string } as R;
if (replacements.length >= index + 1) {
const replacement = replacements[index];
toAdd = addTextAlts(
toAdd,
typeof replacement === "string"
? { text: replacement }
: replacement,
);
}
return addTextAlts(res, toAdd);
}, {
text: "",
} as R);
}
export function addTextAlts<R extends TextAlts>(base: R | string, ...values: (R | string)[]) {
const keys = new Set(
["text", base, ...values].map(value => {
return typeof value === "string"
? []
: Object.keys(value);
}).flat(),
);
return Object.fromEntries([...keys].map(key => {
return [
key,
values.reduce((res, value) => {
return res + (
Updated: February 26, 2024