40 lines
975 B
TypeScript
40 lines
975 B
TypeScript
const MAGIC = 0x7f5a08f5
|
|
|
|
export interface TemplateString {
|
|
__magic: number
|
|
strings: TemplateStringsArray
|
|
variables: string[]
|
|
}
|
|
|
|
export function t(strings: TemplateStringsArray, ...variables: string[]): TemplateString {
|
|
return { __magic: MAGIC, strings: strings, variables: variables }
|
|
}
|
|
|
|
export function isTemplate(template: any): boolean {
|
|
return template !== null && typeof template === 'object' && template.__magic === MAGIC
|
|
}
|
|
|
|
export function expandTemplate(template: TemplateString, content: any): string {
|
|
const values = template.variables.map(path =>
|
|
path.split('.').reduce((acc, key) => {
|
|
if (acc && typeof acc === 'object' && key in acc) {
|
|
return acc[key]
|
|
}
|
|
|
|
return undefined
|
|
}, content)
|
|
)
|
|
|
|
let result = ''
|
|
|
|
for (let i = 0; i < template.strings.length; i++) {
|
|
result += template.strings[i]
|
|
|
|
if (i < values.length) {
|
|
result += values[i] ?? `\${${template.variables[i]}}`
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|