@cloudpss/template
Version:
Lightweight string and object templating utilities with interpolation and formula support.
57 lines (51 loc) • 1.57 kB
text/typescript
import { compileSync, type VmScript } from '@mirascript/mirascript';
import { LRUCache } from 'lru-cache';
/** 字符串模板 */
export type Template =
| string
| {
type: TemplateType;
value: VmScript;
};
/** 字符串模板类型 */
export type TemplateType = 'interpolation' | 'formula';
const CACHE_SIZE = 100;
const formula = new LRUCache<string, Template & { type: 'formula' }>({
max: CACHE_SIZE,
memoMethod: (template: string) => {
const formula = template.slice(1);
const value = compileSync(formula, { input_mode: 'Script' });
return {
type: 'formula',
value: value,
};
},
});
const interpolation = new LRUCache<string, Template & { type: 'interpolation' }>({
max: CACHE_SIZE,
memoMethod: (template: string) => {
const expr = template.slice(1);
const value = compileSync(expr, { input_mode: 'Template' });
return {
type: 'interpolation',
value: value,
};
},
});
/**
* 解析字符串模板
* - 长度大于 1
* - 如果模板以 `=` 开头,则表示是一个公式
* - 如果模板以 `$` 开头,则表示是一个插值模板
* - 否则表示是一个普通字符串
*/
export function parseTemplate(template: string): Template {
if (template.length <= 1) return template;
if (template.startsWith('=')) {
return formula.memo(template);
}
if (template.startsWith('$')) {
return interpolation.memo(template);
}
return template;
}