jws-frontend/src/utils/string-template.ts

54 lines
1.2 KiB
TypeScript
Raw Normal View History

const templates = {
'my-template': {
converter: (context?: number[]) => {
return context?.join(', ') || '';
},
},
2024-11-27 12:55:38 +07:00
'quotation-payment': {
converter: (context?: {
paymentType: 'full' | 'installments';
installments: {
date: string;
amount: number;
}[];
}) => {
return (
context?.installments
.map(
(v) =>
`asdasd
`,
)
.join(', ') || ''
);
},
},
} as const;
type Template = typeof templates;
type TemplateName = keyof Template;
type TemplateContext = {
2024-11-27 12:55:38 +07:00
[key in TemplateName]: Parameters<Template[key]['converter']>[0];
};
export function convertTemplate(
text: string,
context?: TemplateContext,
templateUse?: TemplateName[],
) {
let ret = text;
for (const [name, template] of Object.entries(templates)) {
if (templateUse && !templateUse.includes(name as TemplateName)) continue;
ret = text.replace(
new RegExp('\\#\\[' + name.replaceAll('-', '\\-') + '\\]', 'g'),
typeof template.converter === 'function'
2024-11-27 12:55:38 +07:00
? template.converter(context?.[name as TemplateName] as any)
: template.converter,
);
}
return ret;
}